按单词而不是字符匹配更改

match changes by words, not by characters

我正在使用 difflibSequenceMatcherget_opcodes(),然后使用 css 突出显示更改以创建某种网络 diff

首先,我设置了一个 min_delta,如果整个字符串中只有 3 个或更多字符不同,我认为两个字符串是不同的,一个接一个(delta 表示一个真实的,遇到的增量,总结了所有一个字符的变化):

matcher = SequenceMatcher(source_str, diff_str)
min_delta = 3
delta = 0

for tag, i1, i2, j1, j2 in matcher.get_opcodes():
    if tag == "equal":
        continue  # nothing to capture here
    elif tag == "delete":
        if source_str[i1:i2].isspace():
            continue  # be whitespace-agnostic
        else:
            delta += (i2 - i1)  # delete i2-i1 chars
    elif tag == "replace":
        if source_str[i1:i2].isspace() or diff_str[j1:j2].isspace():
            continue  # be whitespace-agnostic
        else:
            delta += (i2 - i1)  # replace i2-i1 chars
    elif tag == "insert":
        if diff_str[j1:j2].isspace():
            continue  # be whitespace-agnostic
        else:
            delta += (j2 - j1)  # insert j2-j1 chars

return_value = True if (delta > min_delta) else False

这有助于我确定两个字符串是否真的不同。效率不是很高,但我觉得没有什么更好的了。

然后,我以相同的方式对两个字符串之间的差异进行着色:

for tag, i1, i2, j1, j2 in matcher.get_opcodes():
    if tag == "equal":
        # bustling with strings, inserting them in <span>s and colorizing
    elif tag == "delete":
        # ...

return_value = old_string, new_string

结果看起来很难看(蓝色表示已替换,绿色表示新的,红色表示已删除,没有任何内容表示相等):

所以,这是因为 SequenceMatcher 匹配 每个字符 。但我希望它匹配 每个单词 (可能还有它们周围的空格),或者更吸引眼球的东西,因为正如您在屏幕截图上看到的那样,第一本书实际上是移动到第四位。

在我看来,可以用 SequenceMatcherisjunkautojunk 参数来完成一些事情,但我不知道如何写 lambdas为了我的目的。

因此,我有两个问题:

  1. 是否可以按单词匹配?可以使用 get_opcodes()SequenceMatcher 吗?如果没有,可以用什么代替?

  2. 好吧,这是一个推论,但尽管如此:如果可以通过单词进行匹配,那么我就可以摆脱使用 min_delta 和 return True 只要至少有一个词不同,对吗?

SequenceMatcher 可以接受 str 的列表作为输入。

您可以先将输入拆分成单词,然后使用SequenceMatcher帮助您区分单词。那么你的彩色差异将是 by words 而不是 by characters.

>>> def my_get_opcodes(a, b):
...     s = SequenceMatcher(None, a, b)
...     for tag, i1, i2, j1, j2 in s.get_opcodes():
...         print('{:7}   a[{}:{}] --> b[{}:{}] {!r:>8} --> {!r}'.format(
...             tag, i1, i2, j1, j2, a[i1:i2], b[j1:j2]))
... 

>>> my_get_opcodes("qabxcd", "abycdf")
delete    a[0:1] --> b[0:0]      'q' --> ''
equal     a[1:3] --> b[0:2]     'ab' --> 'ab'
replace   a[3:4] --> b[2:3]      'x' --> 'y'
equal     a[4:6] --> b[3:5]     'cd' --> 'cd'
insert    a[6:6] --> b[5:6]       '' --> 'f'

# This is the bad result you currently have.
>>> my_get_opcodes("one two three\n", "ore tree emu\n")
equal     a[0:1] --> b[0:1]      'o' --> 'o'
replace   a[1:2] --> b[1:2]      'n' --> 'r'
equal     a[2:5] --> b[2:5]    'e t' --> 'e t'
delete    a[5:10] --> b[5:5]  'wo th' --> ''
equal     a[10:13] --> b[5:8]    'ree' --> 'ree'
insert    a[13:13] --> b[8:12]       '' --> ' emu'
equal     a[13:14] --> b[12:13]     '\n' --> '\n'

>>> my_get_opcodes("one two three\n".split(), "ore tree emu\n".split())
replace   a[0:3] --> b[0:3] ['one', 'two', 'three'] --> ['ore', 'tree', 'emu']

# This may be the result you want.
>>> my_get_opcodes("one two emily three ha\n".split(), "ore tree emily emu haha\n".split())
replace   a[0:2] --> b[0:2] ['one', 'two'] --> ['ore', 'tree']
equal     a[2:3] --> b[2:3] ['emily'] --> ['emily']
replace   a[3:5] --> b[3:5] ['three', 'ha'] --> ['emu', 'haha']

# A more complicated example exhibiting all four kinds of opcodes.
>>> my_get_opcodes("one two emily three yo right end\n".split(), "ore tree emily emu haha yo yes right\n".split())
replace   a[0:2] --> b[0:2] ['one', 'two'] --> ['ore', 'tree']
equal     a[2:3] --> b[2:3] ['emily'] --> ['emily']
replace   a[3:4] --> b[3:5] ['three'] --> ['emu', 'haha']
equal     a[4:5] --> b[5:6]   ['yo'] --> ['yo']
insert    a[5:5] --> b[6:7]       [] --> ['yes']
equal     a[5:6] --> b[7:8] ['right'] --> ['right']
delete    a[6:7] --> b[8:8]  ['end'] --> []

您还可以按行按书籍按段。你只需要准备一个函数,可以将整个段落字符串预处理成所需的差异块。

例如:

  • 按行区分 - 你可能可以使用splitlines()
  • To diff by book - 你可能可以实现一个函数来剥离 1., 2.
  • 通过分段 区分 - 你可以像这样 API ([book_1, author_1, year_1, book_2, author_2, ...], [book_1, author_1, year_1, book_2, author_2, ...])。然后你的着色将是 by segment.