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

nac*_*cab 7 python diff

我正在尝试找到一种Python 方法来区分字符串。我知道,difflib但我一直没能找到一个内联模式,它的功能与这个 JS 库的功能类似(插入为绿色,删除为红色):

one_string =   "beep boop"
other_string = "beep boob blah"
Run Code Online (Sandbox Code Playgroud)

彩色差异

有办法实现这一点吗?

Dav*_*cco 11

一种可能的方法(另请参阅@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
Run Code Online (Sandbox Code Playgroud)

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

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

print(get_edits_string(one_string, other_string))
Run Code Online (Sandbox Code Playgroud)

彩色差异


Mat*_*nez 1

尝试基于“最小编辑距离”的解决方案,在本例中,我使用此算法来计算距离矩阵。之后,矩阵上的迭代从前到后确定字符串中包含或删除的字符,因为这我需要反转结果。

为了给终端着色,我使用 colorama 模块。

#!/bin/python

import sys
from colorama import *
from numpy import zeros

init()

inv_WHITE = Fore.WHITE[::-1]
inv_RED = Fore.RED[::-1]
inv_GREEN = Fore.GREEN[::-1]

def edDistDp(y, x):
        res = inv_WHITE
        D = zeros((len(x)+1, len(y)+1), dtype=int)
        D[0, 1:] = range(1, len(y)+1)
        D[1:, 0] = range(1, len(x)+1)
        for i in xrange(1, len(x)+1):
                for j in xrange(1, len(y)+1):
                        delt = 1 if x[i-1] != y[j-1] else 0
                        D[i, j] = min(D[i-1, j-1]+delt, D[i-1, j]+1, D[i, j-1]+1)
        #print D

        # iterate the matrix's values from back to forward
        i = len(x)
        j = len(y)
        while i > 0 and j > 0:
                diagonal = D[i-1, j-1]
                upper = D[i, j-1]
                left = D[i-1, j]

                # check back direction
                direction = "\\" if diagonal <= upper and diagonal <= left else "<-" if left < diagonal and left <= upper else "^"
                #print "(",i,j,")",diagonal, upper, left, direction
                i = i-1 if direction == "<-" or direction == "\\" else i
                j = j-1 if direction == "^" or direction == "\\" else j
                # Colorize caracters
                if (direction == "\\"):
                        if D[i+1, j+1] == diagonal:
                                res += x[i] + inv_WHITE
                        elif D[i+1, j+1] > diagonal:
                                res += y[j] + inv_RED
                                res += x[i] + inv_GREEN
                        else:
                                res += x[i] + inv_GREEN
                                res += y[j] + inv_RED
                elif (direction == "<-"):
                        res += x[i] + inv_GREEN
                elif (direction == "^"):
                        res += y[j] + inv_RED
        return res[::-1]

one_string =   "beep boop"
other_string = "beep boob blah"
print ("'%s'-'%s'='%s'" % (one_string, other_string, edDistDp(one_string, other_string)))
print ("'%s'-'%s'='%s'" % (other_string, one_string, edDistDp(other_string, one_string)))

other_string = "hola nacho"
one_string =   "hola naco"
print ("'%s'-'%s'='%s'" % (one_string, other_string, edDistDp(one_string, other_string)))
print ("'%s'-'%s'='%s'" % (other_string, one_string, edDistDp(other_string, one_string)))
Run Code Online (Sandbox Code Playgroud)