0
我有OCR掃描了大量文檔,並且需要在掃描的文件中標識關鍵字。問題是,因爲OCR是不可靠的 - 例如「SUBSCRIPTION」這個詞可能最終成爲「SUBSCR | P || ON」 - 我需要搜索附近的匹配而不是完全匹配。Ruby - 搜索相似字的文件
有誰知道如何搜索文件中的單詞「SUBSCRIPTION」,並返回true,如果找到80%的匹配?
我有OCR掃描了大量文檔,並且需要在掃描的文件中標識關鍵字。問題是,因爲OCR是不可靠的 - 例如「SUBSCRIPTION」這個詞可能最終成爲「SUBSCR | P || ON」 - 我需要搜索附近的匹配而不是完全匹配。Ruby - 搜索相似字的文件
有誰知道如何搜索文件中的單詞「SUBSCRIPTION」,並返回true,如果找到80%的匹配?
看看gem Amatch,找到here。這顆寶石實現了幾種距離算法。另外,閱讀另一個answer關於Levenshtein和Jaro距離算法之間的區別,並檢查哪一個更適合您。
TL; DR,這裏是一小段代碼,幫助您開始解決您的問題,使用Amatch寶石。
'subscription'.levenshtein_similar('SUBSCR|P||ON') #=> 0.0
'SUBSCRIPTION'.levenshtein_similar('SUBSCR|P||ON') #=> 0.75
'subscription'.jaro_similar('SUBSCR|P||ON') #=> 0.83
'SUBSCRIPTION'.jaro_similar('SUBSCR|P||ON') #=> 0.83
'subscription'.jarowinkler_similar('SUBSCR|P||ON') #=> 0.9
'SUBSCRIPTION'.jarowinkler_similar('SUBSCR|P||ON') #=> 0.9
如果你要評估一個給定的文本有一個詞的任何事件,試試這個:
def occurs?(text, target_word)
text_words = text.split(' ') # Splits the text into an array of words.
text_words.each do |word|
return true if word.jaro_similar(target_word) > 0.8
end
false
end
example_text = 'This text has the word SUBSCR|P||ON malformed.'
other_text = 'This text does not.'
occurs?(example_text, 'SUBSCRIPTION') #=> true
occurs?(other_text, 'SUBSCRIPTION') #=> false
請注意,您可以調用方法#downcase
到文本的話也一樣,如果你喜歡。你必須先解析原始文件的文本內容。希望這可以幫助!
也許[Levenshtein距離](https://en.wikipedia.org/wiki/Levenshtein_distance)可能在這方面很有用。在[Rubygems](https://rubygems.org/search?query=Levenshtein)上有這個算法的一些實現。 – spickermann