在python中,有没有一种方法可以获得变化的偏移量以及变化本身?
我所拥有的是:
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.']我还可以获得相应更改的偏移量吗?天真的解决方案可能只是搜索更改,但如果字符串变得更长,重复的术语,这将不起作用。
发布于 2015-07-14 02:18:09
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 elementshttps://docs.python.org/2/library/difflib.html#difflib.SequenceMatcher.get_matching_blocks https://docs.python.org/2/library/difflib.html#sequencematcher-examples
https://stackoverflow.com/questions/31389833
复制相似问题