计算两个字符串相(或句子)似度的方法

简介: 主要方法有:编辑距离、余弦相似度、模糊相似度百分比

主要方法有:编辑距离、余弦相似度、模糊相似度百分比


1 编辑距离



def levenshtein(first, second):
        ''' 编辑距离算法(LevD) 
            Args: 两个字符串
            returns: 两个字符串的编辑距离 int
        '''
        if len(first) > len(second):
            first, second = second, first
        if len(first) == 0:
            return len(second)
        if len(second) == 0:
            return len(first)
        first_length = len(first) + 1
        second_length = len(second) + 1
        distance_matrix = [list(range(second_length)) for x in range(first_length)]
        # print distance_matrix
        for i in range(1, first_length):
            for j in range(1, second_length):
                deletion = distance_matrix[i - 1][j] + 1
                insertion = distance_matrix[i][j - 1] + 1
                substitution = distance_matrix[i - 1][j - 1]
                if first[i - 1] != second[j - 1]:
                    substitution += 1
                distance_matrix[i][j] = min(insertion, deletion, substitution)
                # print distance_matrix
        return distance_matrix[first_length - 1][second_length - 1]


str1="hello,good moring"
str2="hi,good moring"
edit_distance=levenshtein(str1,str2)
edit_distance


4


2 余弦相似度


60.png


61.png


import math
import re
import datetime
import time
text1 = "This game is one of the very best. games ive  played. the  ;pictures? " \
        "cant descripe the real graphics in the game."
text2 = "this game have/ is3 one of the very best. games ive  played. the  ;pictures? " \
        "cant descriPe now the real graphics in the game."
text3 = "So in the picture i saw a nice size detailed metal puzzle. Eager to try since I enjoy 3d wood puzzles, i ordered it. Well to my disappointment I got in the mail a small square about 4 inches around. And to add more disappointment when I built it it was smaller than the palm of my hand. For the price it should of been much much larger. Don't be fooled. It's only worth $5.00.Update 4/15/2013I have bought and completed 13 of these MODELS from A.C. Moore for $5.99 a piece, so i stand by my comment that thiss one is overpriced. It was still fun to build just like all the others from the maker of this brand.Just be warned, They are small."
text4 = "I love it when an author can bring you into their made up world and make you feel like a friend, confidant, or family. Having a special child of my own I could relate to the teacher and her madcap class. I've also spent time in similar classrooms and enjoyed the uniqueness of each and every child. Her story drew me into their world and had me laughing so hard my family thought I had lost my mind, so I shared the passage so they could laugh with me. Read this book if you enjoy a book with strong women, you won't regret it."
def compute_cosine(text_a, text_b):
    # 找单词及词频
    words1 = text_a.split(' ')
    words2 = text_b.split(' ')
    # print(words1)
    words1_dict = {}
    words2_dict = {}
    for word in words1:
        # word = word.strip(",.?!;")
        word = re.sub('[^a-zA-Z]', '', word)
        word = word.lower()
        # print(word)
        if word != '' and word in words1_dict: # 这里改动了
            num = words1_dict[word]
            words1_dict[word] = num + 1
        elif word != '':
            words1_dict[word] = 1
        else:
            continue
    for word in words2:
        # word = word.strip(",.?!;")
        word = re.sub('[^a-zA-Z]', '', word)
        word = word.lower()
        if word != '' and word in words2_dict:
            num = words2_dict[word]
            words2_dict[word] = num + 1
        elif word != '':
            words2_dict[word] = 1
        else:
            continue
    print(words1_dict)
    print(words2_dict)
    # 排序
    dic1 = sorted(words1_dict.items(), key=lambda asd: asd[1], reverse=True)
    dic2 = sorted(words2_dict.items(), key=lambda asd: asd[1], reverse=True)
    print(dic1)
    print(dic2)
    # 得到词向量
    words_key = []
    for i in range(len(dic1)):
        words_key.append(dic1[i][0])  # 向数组中添加元素
    for i in range(len(dic2)):
        if dic2[i][0] in words_key:
            # print 'has_key', dic2[i][0]
            pass
        else:  # 合并
            words_key.append(dic2[i][0])
    # print(words_key)
    vect1 = []
    vect2 = []
    for word in words_key:
        if word in words1_dict:
            vect1.append(words1_dict[word])
        else:
            vect1.append(0)
        if word in words2_dict:
            vect2.append(words2_dict[word])
        else:
            vect2.append(0)
    print(vect1)
    print(vect2)
    # 计算余弦相似度
    sum = 0
    sq1 = 0
    sq2 = 0
    for i in range(len(vect1)):
        sum += vect1[i] * vect2[i]
        sq1 += pow(vect1[i], 2)
        sq2 += pow(vect2[i], 2)
    try:
        result = round(float(sum) / (math.sqrt(sq1) * math.sqrt(sq2)), 2)
    except ZeroDivisionError:
        result = 0.0
    # print(result)
    return result
if __name__ == '__main__':
    result=compute_cosine(text1, text2)
    print(result)


{'this': 1, 'game': 2, 'is': 1, 'one': 1, 'of': 1, 'the': 4, 'very': 1, 'best': 1, 'games': 1, 'ive': 1, 'played': 1, 'pictures': 1, 'cant': 1, 'descripe': 1, 'real': 1, 'graphics': 1, 'in': 1}
{'this': 1, 'game': 2, 'have': 1, 'is': 1, 'one': 1, 'of': 1, 'the': 4, 'very': 1, 'best': 1, 'games': 1, 'ive': 1, 'played': 1, 'pictures': 1, 'cant': 1, 'descripe': 1, 'now': 1, 'real': 1, 'graphics': 1, 'in': 1}
[('the', 4), ('game', 2), ('this', 1), ('is', 1), ('one', 1), ('of', 1), ('very', 1), ('best', 1), ('games', 1), ('ive', 1), ('played', 1), ('pictures', 1), ('cant', 1), ('descripe', 1), ('real', 1), ('graphics', 1), ('in', 1)]
[('the', 4), ('game', 2), ('this', 1), ('have', 1), ('is', 1), ('one', 1), ('of', 1), ('very', 1), ('best', 1), ('games', 1), ('ive', 1), ('played', 1), ('pictures', 1), ('cant', 1), ('descripe', 1), ('now', 1), ('real', 1), ('graphics', 1), ('in', 1)]
[4, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0]
[4, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
0.97


3 FuzzyWuzzy



from fuzzywuzzy import fuzz
fuzz.ratio("this is a test", "this is a test!")


97


4 difflib 字符串比较


ratio()返回两个字符串之间的相似度,范围是[0,1]


62.png


def get_diffs(text1,text2):
    """获取diff 距离"""
    print("get diffs ratios...")
    seq=difflib.SequenceMatcher()
    diffs=[]
    for wid1,wid2 in tqdm(zip(text1,text2)):
        seq.set_seqs(wid1.lower(),wid2.lower())
        diffs.append(seq.ratio())
    return diffs


difflib模块的其他用法请看:

相关文章
|
SQL XML 架构师
SpringBoot从小白到精通(十六)使用pagehelper实现分页查询功能
之前讲了Springboot整合Mybatis,然后介绍了如何自动生成pojo实体类、mapper类和对应的mapper.xml 文件,并实现最基本的增删改查功能。接下来要说一说Mybatis 的分页功能:使用Mybatis-PageHelper插件,实现分页功能。
SpringBoot从小白到精通(十六)使用pagehelper实现分页查询功能
|
存储 人工智能 Java
AI 超级智能体全栈项目阶段二:Prompt 优化技巧与学术分析 AI 应用开发实现上下文联系多轮对话
本文讲解 Prompt 基本概念与 10 个优化技巧,结合学术分析 AI 应用的需求分析、设计方案,介绍 Spring AI 中 ChatClient 及 Advisors 的使用。
3287 134
AI 超级智能体全栈项目阶段二:Prompt 优化技巧与学术分析 AI 应用开发实现上下文联系多轮对话
|
人工智能 机器人 API
使用 通义千问(Qwen) 大模型进行编程应用开发
本文介绍了使用阿里云Qwen API开发编程应用的核心流程,包括获取API密钥、安装SDK、编写调用代码,以及实现智能代码生成、多轮对话等场景。内容涵盖环境配置、代码示例与安全建议,助你快速构建基于大模型的编程工具。
7944 2
|
人工智能 Java API
教你自创工作流,赋予AI助理个性化推荐超能力
本文详细介绍了使用Spring AI Alibaba构建AI助理的全过程,涵盖从基本流程设计到实际操作实现的各个方面。文章首先回顾了前期工作,包括旅游攻略、天气查询和个人待办事项等功能模块的设计与实现。接着,深入探讨了工作流的实现细节,如事件封装优化、工作流节点创建及复杂工作流的高效管理。最后,通过实际项目启动与运行测试,展示了AI助理的实际效果,验证了系统的稳定性和可扩展性。本文不仅适合Java开发者学习AI技术,也为后续的优化和功能拓展提供了宝贵的经验。
2519 9
教你自创工作流,赋予AI助理个性化推荐超能力
|
JSON 缓存 API
技术解析:如何通过淘宝开放平台API获取商品券后价
本文介绍如何通过淘宝开放平台API(taobao.tbk.item.coupon.get)合法获取商品优惠券信息,并结合原价计算券后价。涵盖接口调用流程、参数说明、Python示例代码及签名生成、错误处理、频率限制等注意事项,助力开发者高效实现电商比价与优惠聚合功能。(238字)
|
存储 缓存 JavaScript
如何优化Node.js应用的内存使用以提高性能?
通过以上多种方法的综合运用,可以有效地优化 Node.js 应用的内存使用,提高性能,提升用户体验。同时,不断关注内存管理的最新技术和最佳实践,持续改进应用的性能表现。
1026 62
|
SQL 关系型数据库 MySQL
删库,误清数据怎么办?MySQL数据恢复指南
相信很多同学在面对线上数据库时都畏手畏脚,即使这样都难免手滑,一不小心手一抖就将数据或者是表,库删除。当然一些注重规范的公司,不会给开发人员删除表或者是库的权限,但误删数据是常有的事,那么这种情况发生,我们改怎么办呢?跑路?哈哈,当然删库跑路是句玩笑话,本文就为大家介绍一些数据误删除恢复的办法。
4612 0
|
数据采集 SQL 数据挖掘
电商数据分析的方法
电商数据分析涵盖从业务需求理解到数据呈现的全流程。初学者应循序渐进,掌握数据清洗、转换等技能,Python是重要工具。社交媒体营销分析关注用户参与度和KOL影响。实战教程如《2019电商数据分析师实战项目》提供Excel、SQL及Tableau应用案例,帮助巩固理论知识。代码示例展示了如何使用Pandas和SQLAlchemy进行销售数据分析,计算转化率。 (注:联系方式和感谢语已省略以符合要求)
电商数据分析的方法
|
人工智能 自然语言处理 搜索推荐
谈谈Function Calling
Function Calling赋予大语言模型调用外部工具的能力,弥补其缺乏行动力、信息滞后等缺陷。它像“指挥家”般,理解用户意图,选择合适的工具执行操作,并将结果反馈给用户,从而连接虚拟与现实。这一机制让大语言模型如虎添翼,更好地服务于人类。
1460 3
谈谈Function Calling
|
传感器 物联网 定位技术
浅谈蓝牙演进之路:从诞生到普及
蓝牙技术是一种支持设备间短距离通信的低功耗无线电技术,广泛应用于移动通信、消费电子、汽车电子、医疗健康等领域。自1994年由爱立信公司创制以来,蓝牙技术经历了多个版本的迭代,从最初的蓝牙1.0到最新的蓝牙5.4,不断优化传输速率、通信距离、功耗和安全性。未来,蓝牙技术将在低功耗、高速度、广覆盖等方面继续发展,拓展更多应用场景,如智能家居、可穿戴设备、工业物联网等。
3677 19