gpt4 book ai didi

python - 如何用颜色显示两个字符串序列的差异?

转载 作者:太空宇宙 更新时间:2023-11-04 01:01:43 26 4
gpt4 key购买 nike

我正在尝试寻找一种 Python 方法来区分字符串。我知道 difflib 但我一直没能找到一个内联模式来做类似于 this JS library 的事情。做(绿色插入,红色删除):

one_string =   "beep boop"
other_string = "beep boob blah"

colored diff

有什么办法可以实现吗?

最佳答案

一种可能的方式(另见@interjay 对 OP 的评论)是

import difflib

red = lambda text: f"\033[38;2;255;0;0m{text}\033[38;2;255;255;255m"
green = lambda text: f"\033[38;2;0;255;0m{text}\033[38;2;255;255;255m"
blue = lambda text: f"\033[38;2;0;0;255m{text}\033[38;2;255;255;255m"
white = lambda text: f"\033[38;2;255;255;255m{text}\033[38;2;255;255;255m"

def get_edits_string(old, new):
result = ""
codes = difflib.SequenceMatcher(a=old, b=new).get_opcodes()
for code in codes:
if code[0] == "equal":
result += white(old[code[1]:code[2]])
elif code[0] == "delete":
result += red(old[code[1]:code[2]])
elif code[0] == "insert":
result += green(new[code[3]:code[4]])
elif code[0] == "replace":
result += (red(old[code[1]:code[2]]) + green(new[code[3]:code[4]]))
return result

这仅取决于 difflib,并且可以用

进行测试
one_string =   "beep boop"
other_string = "beep boob blah"

print(get_edits_string(one_string, other_string))

colored diff

关于python - 如何用颜色显示两个字符串序列的差异?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32500167/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com