QQ登录

只需要一步,快速开始

 注册地址  找回密码
查看: 1099|回复: 0
打印 上一主题 下一主题

python 比较和处理文本之间的差异

[复制链接]
字体大小: 正常 放大

1175

主题

4

听众

2861

积分

该用户从未签到

跳转到指定楼层
1#
发表于 2024-3-31 11:12 |只看该作者 |倒序浏览
|招呼Ta 关注Ta
  • difflib是Python标准库中的一个模块,用于比较和处理文本之间的差异。它提供了一些函数和类,可以用于生成差异报告、计算相似度、查找最长公共子序列等操作。
    安装内置库 无需安装常见用法1:比较差异
    1. import difflib

    2. text1 = "hello world"
    3. text2 = "hello there"

    4. diff = difflib.ndiff(text1, text2)
    5. print('\n'.join(diff))
    复制代码
    常见用法2:比较文件的差异
    1. import difflib

    2. with open('file1.txt') as file1, open('file2.txt') as file2:
    3.     diff = difflib.ndiff(file1.readlines(), file2.readlines())
    4.     print('\n'.join(diff))
    复制代码
    常见用法3:比较列表的差异
    1. import difflib

    2. list1 = ['apple', 'banana', 'cherry']
    3. list2 = ['apple', 'banana', 'kiwi']

    4. diff = difflib.ndiff(list1, list2)
    5. print('\n'.join(diff))
    复制代码

    常见用法4:比较字符串相似度
    1. import difflib

    2. text1 = "hello world"
    3. text2 = "hello there"

    4. similarity = difflib.SequenceMatcher(None, text1, text2).ratio()
    5. print(similarity)
    复制代码

    输出,相似度 百分之63.6%0.6363636363636364常见用法5:获取两个字符串的相似块:
    1. import difflib

    2. text1 = "hello world"
    3. text2 = "hello there"

    4. blocks = difflib.SequenceMatcher(None, text1, text2).get_matching_blocks()
    5. print(blocks)
    复制代码

    输出[Match(a=0, b=0, size=6), Match(a=8, b=9, size=1), Match(a=11, b=11, size=0)]
  • 常见用法6:获取两个字符串的最长公共子序列
    1. import difflib
    2. text1 = "hello world"
    3. text2 = "hello there"

    4. lcs = difflib.SequenceMatcher(None, text1, text2).find_longest_match(0, len(text1), 0, len(text2))
    5. print(lcs)
    复制代码
    输出Match(a=0, b=0, size=6)
    1. import difflib

    2. text1 = "hello world"
    3. text2 = "hello there"

    4. lcs = difflib.SequenceMatcher(None, text1, text2).find_longest_match(0, len(text1), 0, len(text2))
    5. print(text1[lcs.a: lcs.a + lcs.size])
    复制代码
    输出hello 常见用法7:比较两个字符串,并返回上下文差异
    1. import difflib

    2. text1 = "hello world"
    3. text2 = "hello there"

    4. diff = difflib.context_diff(text1, text2)
    5. print('\n'.join(diff)
    复制代码




zan
转播转播0 分享淘帖0 分享分享0 收藏收藏0 支持支持0 反对反对0 微信微信
您需要登录后才可以回帖 登录 | 注册地址

qq
收缩
  • 电话咨询

  • 04714969085
fastpost

关于我们| 联系我们| 诚征英才| 对外合作| 产品服务| QQ

手机版|Archiver| |繁體中文 手机客户端  

蒙公网安备 15010502000194号

Powered by Discuz! X2.5   © 2001-2013 数学建模网-数学中国 ( 蒙ICP备14002410号-3 蒙BBS备-0002号 )     论坛法律顾问:王兆丰

GMT+8, 2025-8-14 04:18 , Processed in 0.450641 second(s), 50 queries .

回顶部