首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python difflib,获取偏移量

Python difflib,获取偏移量
EN

Stack Overflow用户
提问于 2015-07-14 01:33:20
回答 1查看 145关注 0票数 3

在python中,有没有一种方法可以获得变化的偏移量以及变化本身?

我所拥有的是:

代码语言:javascript
复制
import difflib

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

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

打印的内容:

代码语言:javascript
复制
['  this', '  is', '- a', '- sample', '  text', '+ two.']

我还可以获得相应更改的偏移量吗?天真的解决方案可能只是搜索更改,但如果字符串变得更长,重复的术语,这将不起作用。

EN

回答 1

Stack Overflow用户

发布于 2015-07-14 02:18:09

SequenceMatcher.get_matching_blocks()可能会有所帮助。它返回一个描述匹配子序列的三元组列表。这些索引反过来可以用来找出差异的位置。

代码语言:javascript
复制
>>> 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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31389833

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档