假设有一段英文,其中有单独的字母“I”误写为“i”,请编写程序进行纠正。
这里给出Python 3.4.2代码,如果使用Python 2.7.8的话只需要修改其中的print()函数为print语句即可。
1)不使用正则表达式
x = "i am a teacher,i am man, and i am 38 years old.I am not a businessman." x = x.replace('i ','I ') x = x.replace(' i ',' I ') print(x)
2)使用正则表达式
x = "i am a teacher,i am man, and i am 38 years old.I am not a businessman." import re pattern = re.compile(r'(?:[^\w]|\b)i(?:[^\w])') while True: result = pattern.search(x) if result: if result.start(0) != 0: x = x[:result.start(0)+1]+'I'+x[result.end(0)-1:] else: x = x[:result.start(0)]+'I'+x[result.end(0)-1:] else: break print(x)
#coding=utf-8
#https://www.nowcoder.com/questionTerminal/931fa0aed84a44d38d7ea792fdfdc12b?orderByHotValue=1&questionTypes=000010&mutiTagIds=573&page=3&onlyReference=false#假设有一段英文,其中有单独的字母“I”误写为“i”,请编写程序进行纠正。
#假设有一段英文,其中有单独的字母“I”误写为“i”,请编写程序进行纠正。
import re
x = "i am a teacher,i am man, and i am 38 years old.i am not a businessman."
pattern = re.compile(r'(?:[^\w]|\b)i(?:[^\w])')
while True:
result = pattern.search(x)
if result:
if result.start(0) != 0:
x = x[:result.start(0)+1]+'I'+x[result.end(0)-1:]
else:
x = x[:result.start(0)]+'I'+x[result.end(0)-1:]
else:
break
print x