Python difflib,获取偏移量
在python中,有没有一种使用difflib的方法可以获得更改的偏移量以及更改本身 我所拥有的是:Python difflib,获取偏移量,python,Python,在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.']
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.']
我还可以得到相应变化的偏移量吗?
简单的解决方案是只搜索更改,但如果字符串因重复的术语而变长,这将不起作用 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