Python - 中文文本相似度计算与模糊匹配
    		       		warning:
    		            这篇文章距离上次修改已过439天,其中的内容可能已经有所变动。
    		        
        		                
                
import difflib
 
def calculate_similarity(text1, text2):
    """
    计算两个字符串的相似度
    :param text1: 第一个字符串
    :param text2: 第二个字符串
    :return: 相似度百分比
    """
    # 使用difflib库的SequenceMatcher来计算相似度
    similarity = difflib.SequenceMatcher(None, text1, text2).ratio()
    return similarity
 
def fuzzy_matching(candidates, query):
    """
    对候选集进行模糊匹配
    :param candidates: 候选集
    :param query: 查询字符串
    :return: 排序后的候选集
    """
    # 对每个候选项计算与查询的相似度,并以相似度降序排序
    matched_candidates = [(c, calculate_similarity(c, query)) for c in candidates]
    matched_candidates.sort(key=lambda x: x[1], reverse=True)
    return matched_candidates
 
# 示例代码
candidates = ["北京市长城", "北京市天安门", "上海市东方明珠塔"]
query = "北京长城"
matched_results = fuzzy_matching(candidates, query)
for item in matched_results:
    print(f"{item[0]}: {item[1]*100:.2f}%")这段代码首先定义了一个计算字符串相似度的函数calculate_similarity,然后定义了一个模糊匹配函数fuzzy_matching,它使用了difflib库的SequenceMatcher来计算两个字符串的相似度。最后,我们提供了使用这两个函数的示例代码,它将模拟对一个候选集进行模糊匹配,并输出每个匹配结果的相似度。
评论已关闭