[英]Using fuzzy regex (in Python) to correct spelling
我在分析的文本中有一系列常用词,我打算使用正则表达式模糊匹配来替换它们的任何拼写错误。
我知道我可以像这样循环它们:
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
用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)
它使用匹配对象的 lastgroup 属性,该属性告诉您哪个组导致替换触发。 如果您需要,这应该可以很好地扩展到更大的数组,假设 re.compile 没有限制会妨碍您。 希望这可以帮助。 带有 lastgroup 的 Python 文档: https ://docs.python.org/2/library/re.html 方便的正则表达式编辑器可帮助解决未来的问题: https ://regex101.com
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.