Python difflib,获取偏移量

3

在python中,是否有使用difflib库能够得到改变的位置偏移以及改变本身的方法?

我拥有以下内容:

import difflib

text1 = 'this is a sample text'.split()
text2 = 'this is text two.'.split()

print list(difflib.ndiff(text1, text2))

这将打印:

['  this', '  is', '- a', '- sample', '  text', '+ two.']

我也能得到相应更改的偏移量吗?天真的解决方案就是搜索更改,但如果字符串随着重复术语变长,那就不起作用了。

1个回答

2

可以尝试使用SequenceMatcher.get_matching_blocks()函数,返回匹配子序列的三元组列表。然后使用这些索引找到不同之处所在的位置。

>>> for block in s.get_matching_blocks():
...     print "a[%d] and b[%d] match for %d elements" % block
a[0] and b[0] match for 8 elements
a[8] and b[17] match for 21 elements
a[29] and b[38] match for 0 elements

https://docs.python.org/2/library/difflib.html#difflib.SequenceMatcher.get_matching_blocks https://docs.python.org/2/library/difflib.html#sequencematcher-examples


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接