我一直在使用PostgreSQL中pg_trgm模塊的相似性功能,現在我正在Python中搜索類似於相似度的單詞相似性函數。我在Python中找到了很多方法,例如difflib,nltk,但這些方法都沒有產生類似於PostgreSQL相似函數的結果。Python字符串匹配完全等於Postgresql相似函數
我一直在使用這段代碼進行單詞匹配,但結果與PostgreSQL相似度函數的結果大不相同。這些結果是否比PostgreSQL的相似性功能好?有沒有什麼方法或庫可以用來產生類似於PostgreSQL的結果相似度函數?
from difflib import SequenceMatcher
import nltk
from fuzzywuzzy import fuzz
def similar(a,b):
return SequenceMatcher(None,a,b).ratio()
def longest_common_substring(s1, s2):
m = [[0] * (1 + len(s2)) for i in xrange(1 + len(s1))]
longest, x_longest = 0, 0
for x in xrange(1, 1 + len(s1)):
for y in xrange(1, 1 + len(s2)):
if s1[x - 1] == s2[y - 1]:
m[x][y] = m[x - 1][y - 1] + 1
if m[x][y] > longest:
longest = m[x][y]
x_longest = x
else:
m[x][y] = 0
return s1[x_longest - longest: x_longest]
def similarity(s1, s2):
return 2. * len(longest_common_substring(s1, s2))/(len(s1) + len(s2)) * 100
print similarity("New Highway Classic Academy Lahore","Old Highway Classic Academy")
print nltk.edit_distance("This is Your Shop","This")
print fuzz.ratio("ISE-Tower","UfTowerong,")