Unpacking SequenceMatcher循环结果

问题描述 投票:1回答:2

在Python中解压缩SequenceMatcher循环的最佳方法是什么,以便可以轻松地访问和处理值?

from difflib import *

orig = "1234567890"

commented = "123435456353453578901343154"

diff = SequenceMatcher(None, orig, commented)

match_id = []
for block in diff.get_matching_blocks():
    match_id.append(block)

print(match_id)

字符串整数代表汉字。

当前的迭代代码将匹配结果存储在这样的列表中:

match_id
[Match(a=0, b=0, size=4), Match(a=4, b=7, size=2), Match(a=6, b=16, size=4), Match(a=10, b=27, size=0)]

我最终希望像这样用"{{""}}"标记注释:

"1234{{354}}56{{3534535}}7890{{1343154}}"

这意味着,我有兴趣解压缩以上SequenceMatcher的结果,并对特定的bsize值进行一些计算以产生此序列:

rslt = [[0+4,7],[7+2,16],[16+4,27]]

[b[i]+size[i],b[i+1]]的重复。

python iterable-unpacking
2个回答
0
投票

我会这样:

from difflib import *

orig = "1234567890"
commented = "123435456353453578901343154"

diff = SequenceMatcher(None, orig, commented)

match_id = []
rslt_str = ""
for block in diff.get_matching_blocks():
    match_id.append(block)

temp = 0
for i, m in enumerate(match_id[:-1]):
    rslt_str += commented[temp:m.b + m.size] + "{{"
    rslt_str += commented[m.b + m.size: match_id[i+1].b] + "}}"
    temp = match_id[i+1].b

以便rslt_str == "1234{{354}}56{{3534535}}7890{{1343154}}"


0
投票

1。解压SequenceMatcher产生序列

您可以解压缩match_id,然后对表达式使用列表推导。

a, b, size = zip(*match_id)
# a    = (0, 4,  6, 10)
# b    = (0, 7, 16, 27)
# size = (4, 2,  4,  0)

rslt = [[b[i] + size[i], b[i+1]] for i in range(len(match_id)-1)]
# rslt = [[4, 7], [9, 16], [20, 27]]

zip的参考,Python内置函数:https://docs.python.org/3/library/functions.html#zip

2。用"{{""}}"]标记注释

您可以遍历rslt,然后很好地附加当前匹配并标记注释。

rslt_str = ""
prev_end = 0

for start, end in rslt:
    rslt_str += commented[prev_end:start]
    if start != end:
        rslt_str += "{{%s}}" % commented[start:end]
    prev_end = end
# rslt_str = "1234{{354}}56{{3534535}}7890{{1343154}}"
© www.soinside.com 2019 - 2024. All rights reserved.