我希望能够以一种模糊的方式查找和替换。因此,我需要对文本进行模糊搜索,并返回与关键字的模糊匹配,但我正在努力寻找实现这一点的方法。例如,我想这样做:
text = 'The sunset is a lovely colour this evening'
keyword = 'Color'
desired_result = colour
text.replace(desired_result, keyword)
print(text)
The sunset is a lovely Color this evening更复杂的是,需要替换的短语可能不止一个单词,所以拆分是行不通的。
我已经尝试过FuzzyWuzzy的process函数,但这只会返回关键字,而不会返回匹配。例如:
process.extractOne("This sunset is a lovely colour this evening", "Color")
("Color", 90)我需要文本中的匹配项,这样我就可以替换。
Python的正则表达式可以做模糊匹配,但性能是一个问题,它似乎不适合我的完整短语。
text = 'The sunset is a lovely colour this evening'
term = 'Color'
r = regex.compile('('+text +'){e<=5}')
print(r.match(term ))
None发布于 2020-01-13 17:35:57
如果您使用模糊搜索,您可以使用find_near_matches来获取匹配的索引,然后使用列表理解来获取实际使用的字符串
from fuzzysearch import find_near_matches
my_string = 'aaaPATERNaaa'
matches = find_near_matches('PATTERN', my_string, max_l_dist=1)
print([my_string[m.start:m.end] for m in matches])https://stackoverflow.com/questions/59713425
复制相似问题