首页 > 试题广场 >

假设有一段英文,其中有单独的字母“I”误写为“i”,请编写程

[问答题]

假设有一段英文,其中有单独的字母“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)

发表于 2017-12-28 15:45:33 回复(0)

#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

发表于 2018-06-08 13:48:59 回复(0)