2016-06-10 77 views
-1

我有多个PDF转换成文本文件,我想搜索可能在文件中的某个短语。我的问题是,PDF和文本文件之间的转换并不完美,所以有时会出现文本错误(例如字之间缺失空格; i,l,1之间的混淆等)如何匹配可能的拼写错误的字符串?

I想知道是否有任何共同的技术给我一个“软”的搜索,例如看看两个词之间的汉明距离。

if 'word' in sentence: 

VS

if my_search('word',sentence, tolerance): 
+0

这里有一个叫做dista的图书馆nce:https://pypi.python.org/pypi/Distance/0.1 – dagrha

+0

尝试谷歌搜索字符串距离算法 – user853710

回答

1

你可以使用这样的事情:

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) 

这应该输出这样的:

'errors' matches: '3rrors' in line 2 
+1

这工作,谢谢! – kkawabat