Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sql-server-2005/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:使用re.sub多次替换多个子字符串_Python_Replace - Fatal编程技术网

Python:使用re.sub多次替换多个子字符串

Python:使用re.sub多次替换多个子字符串,python,replace,Python,Replace,我试图纠正一个文本,它有一些非常典型的扫描错误(我误认为是I,反之亦然)。基本上,我想让re.sub中的替换字符串取决于检测到“I”的次数,类似于: re.sub((\w+)(I+)(\w*),“\gl+\g”,“我还在这里。”) 实现此目的的最佳方法是什么?传递函数作为替换字符串,如中所述。您的函数可以识别错误并在此基础上创建最佳替换 def replacement(match): if "I" in match.group(2): return match.group

我试图纠正一个文本,它有一些非常典型的扫描错误(我误认为是I,反之亦然)。基本上,我想让
re.sub
中的替换字符串取决于检测到“I”的次数,类似于:

re.sub((\w+)(I+)(\w*),“\gl+\g”,“我还在这里。”)


实现此目的的最佳方法是什么?

传递函数作为替换字符串,如中所述。您的函数可以识别错误并在此基础上创建最佳替换

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出现在一个组中。)

在我看来,您可以执行以下操作:

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.')
您可以使用仅替换
I
s后面或前面的另一个
I

print re.sub("(?<=I)I|I(?=I)", "l", "I am stiII here.")

print re.sub((?基于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)

希望这对其他人有帮助!

您能举出您遇到的其他情况的例子吗?是的;否则第一组中的第一个我会被\w+吞没。谢谢,我没有意识到这种机制的存在。捕获特殊情况而不必使正则表达式复杂化非常有用。我在an中发布了我的最终代码在下面回答。