使用模糊正则表达式(在 Python 中)来纠正拼写



我在分析的文本中有一系列常用单词,我打算使用正则表达式模糊匹配来替换它们的任何拼写错误。

我知道我可以像这样循环它们:

import regex as re
edits = 1
my_arr = ['word1', 'word2', 'word3']
my_text = 'this is my text with wrd1 in it'
for word in my_arr:
    r_pattern = '(' + word + ')' + '){e<=' + str(edits) + '}'
    my_text = re.sub(r_pattern, word, my_text)

但是有没有办法使用regex.sub来用一行来做到这一点?也就是说,所以我的模式可能看起来像

r_pattern = '(word1|word2|word3){e<=1}'
这是我

的解决方案

import regex as re
def repl(matchObj):
    return str(matchObj.lastgroup)
edits = 1
my_arr = ['word1', 'word2', 'word3']
my_text = 'this is my text with wrd3 in it'
r_pattern = ""
for i in range(len(my_arr)):
    if i == len(my_arr)-1:
        r_pattern += '(?P<' + my_arr[i] + '>' + my_arr[i] + '){e<=' + str(edits) + '}'
    else:
        r_pattern += '(?P<' + my_arr[i] + '>' + my_arr[i] + '){e<=' + str(edits) + '}|'
r = re.compile(r_pattern)
my_text = re.sub(r, repl, my_text)
print (my_text)

它使用 match 对象的 lastgroup 属性,该属性告诉您哪个组导致触发替换。如果需要,这应该可以很好地扩展更大的数组,假设 re.compile 没有限制会妨碍您。希望这有帮助。Python Doc with lastgroup: https://docs.python.org/2/library/re.html方便的正则表达式编辑器,以帮助解决未来的问题:https://regex101.com

最新更新