kka*_*bat 1 python string data-processing
我将多个pdf转换为文本文件,并且我想搜索文件中可能存在的特定短语。我的问题是pdf和文本文件之间的转换不完美,因此有时文本中会出现错误(例如单词之间缺少空格; i,l,1之间的混淆;等等)
我想知道是否有任何常用的技术可以让我进行“软”搜索,例如,可以查看两个词之间的汉明距离。
if 'word' in sentence:
Run Code Online (Sandbox Code Playgroud)
与
if my_search('word',sentence, tolerance):
Run Code Online (Sandbox Code Playgroud)
您可以使用以下方式:
from difflib import SequenceMatcher
text = """there are
some 3rrors in my text
but I cannot find them"""
def fuzzy_search(search_key, text, strictness):
lines = text.split("\n")
for i, line in enumerate(lines):
words = line.split()
for word in words:
similarity = SequenceMatcher(None, word, search_key)
if similarity.ratio() > strictness:
return " '{}' matches: '{}' in line {}".format(search_key, word, i+1)
print fuzzy_search('errors', text, 0.8)
Run Code Online (Sandbox Code Playgroud)
应该输出以下内容:
'errors' matches: '3rrors' in line 2
Run Code Online (Sandbox Code Playgroud)