比较字典中不确定数量的字符串,将最佳匹配作为新键进行存储。
创始人
2024-12-15 16:30:04
0

可以采取余弦相似度算法来比较字符串的相似度,代码如下:

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']}

以'best_match'存储最佳匹配

result = best_match(d) print(result)

相关内容

热门资讯

一分钟揭秘(wEpoKe)外挂... 一分钟揭秘(wEpoKe)外挂透明挂辅助工具(智能ai代打)好像真的有挂(2023已更新)(百度);...
一分钟教会你(鱼扑克app俱乐... 一分钟教会你(鱼扑克app俱乐部)外挂透明挂辅助工具(智能ai代打)果真真的有挂(2021已更新)(...
揭秘关于(aaPOKER)外挂... 揭秘关于(aaPOKER)外挂透明挂辅助APP(透视辅助)一贯真的有挂(2025已更新)(哔哩哔哩)...
总算了解(红龙扑克)外挂透明挂... 总算了解(红龙扑克)外挂透明挂辅助APP(透视)好像真的有挂(2021已更新)(抖音);1、透视辅助...
必看攻略(来玩德州app)外挂... 必看攻略(来玩德州app)外挂透明挂辅助工具(透视)都是真的有挂(2022已更新)(头条);1、超多...
盘点一款(aApoker)外挂... 盘点一款(aApoker)外挂透明挂辅助脚本(辅助挂)一贯真的有挂(2024已更新)(知乎)1、这是...
玩家必看教程(we辅助poke... 玩家必看教程(we辅助poker)外挂透明挂辅助器(软件透明挂)原来真的有挂(2021已更新)(抖音...
发现一款(哈糖大菠萝)外挂透明... 发现一款(哈糖大菠萝)外挂透明挂辅助软件(辅助挂)的确是有挂的(2020已更新)(抖音)1、透视辅助...
热点讨论(扑克时间)外挂透明挂... 热点讨论(扑克时间)外挂透明挂辅助软件(智能ai代打)其实真的有挂(2021已更新)(百度贴吧);1...
科技分享(来玩app德州)外挂... 科技分享(来玩app德州)外挂透明挂辅助神器(透视辅助)原来真的有挂(2025已更新)(今日头条)小...