Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/355.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/jquery-ui/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python difflib,获取偏移量_Python - Fatal编程技术网

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.']

在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.']
我还可以得到相应变化的偏移量吗?
简单的解决方案是只搜索更改,但如果字符串因重复的术语而变长,这将不起作用

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