可以采取余弦相似度算法来比较字符串的相似度,代码如下:
from itertools import combinations from math import acos, degrees from collections import defaultdict
def cosine_similarity(text1, text2, factor=0.2): # 文本相似度计算 vec1 = defaultdict(int) for word in text1: vec1[word] += 1 vec2 = defaultdict(int) for word in text2: vec2[word] += 1
common = set(vec1.keys()) & set(vec2.keys())
dot_product = sum([vec1[x] * vec2[x] for x in common])
magnitude1 = sum([vec1[x] ** 2 for x in vec1.keys()])
magnitude2 = sum([vec2[x] ** 2 for x in vec2.keys()])
magnitude = ((magnitude1 * magnitude2) ** 0.5) or 1
similarity = dot_product / magnitude
return similarity + (factor * len(common) / (len(text1) + len(text2)))
def best_match(d):
# 处理多个字符串匹配的情况:
for key1, key2 in combinations(d.keys(), 2):
match_score = cosine_similarity(d[key1], d[key2])
if ('best_match' not in d[key1]) or (match_score > d[key1]['best_match']['score']):
d[key1]['best_match'] = {'term': key2, 'score': match_score}
if ('best_match' not in d[key2]) or (match_score > d[key2]['best_match']['score']):
d[key2]['best_match'] = {'term': key1, 'score': match_score}
return d
d = {'string1': ['hello', 'world'], 'string2': ['world', 'programming', 'python']}
result = best_match(d) print(result)
上一篇:比较字典值并筛选出一些进行排序
下一篇:比较字典中的元素,Swift