我正在尝试更正具有一些非常典型的扫描错误的文本(我误认为是I,反之亦然)。基本上我希望re.sub
中的替换字符串取决于检测到“I”的次数,类似:
re.sub("(\w+)(I+)(\w*)", "\g<1>l+\g<3>", "I am stiII here.")
实现这一目标的最佳方式是什么?
答案 0 :(得分:3)
将函数作为替换字符串传递,如the docs中所述。您的函数可以识别错误并根据该函数创建最佳替换。
def replacement(match):
if "I" in match.group(2):
return match.group(1) + "l" * len(match.group(2)) + match.group(3)
# Add additional cases here and as ORs in your regex
re.sub(r"(\w+)(II+)(\w*)", replacement, "I am stiII here.")
>>> I am still here.
(请注意,我修改了你的正则表达式,因此重复的Is会出现在一个组中。)
答案 1 :(得分:1)
您可以使用lookaround仅替换其他I
之后或之前的I
:
print re.sub("(?<=I)I|I(?=I)", "l", "I am stiII here.")
答案 2 :(得分:0)
在我看来,你可以做类似的事情:
def replace_L(match):
return match.group(0).replace(match.group(1),'l'*len(match.group(1)))
string_I_want=re.sub(r'\w+(I+)\w*',replace_L,'I am stiII here.')
答案 3 :(得分:0)
基于DNS提出的答案,我构建了一些更复杂的东西来捕获所有案例(或至少大部分案例),尽量不添加太多错误:
def Irepl(matchobj):
# Catch acronyms
if matchobj.group(0).isupper():
return matchobj.group(0)
else:
# Replace Group2 with 'l's
return matchobj.group(1) + 'l'*len(matchobj.group(2)) + matchobj.group(3)
# Impossible to know if first letter is correct or not (possibly a name)
I_FOR_l_PATTERN = "([a-zA-HJ-Z]+?)(I+)(\w*)"
for line in lines:
tmp_line = line.replace("l'", "I'").replace("'I", "'l").replace(" l ", " I ")
tmp_line = re.sub("^l ", "I ", tmp_line)
cor_line = re.sub(I_FOR_l_PATTERN, Irepl, tmp_line)
# Loop to catch all errors in a word (iIIegaI for example)
while cor_line != tmp_line:
tmp_line = cor_line
cor_line = re.sub(I_FOR_l_PATTERN, Irepl, tmp_line)
希望这有助于其他人!