在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结果感兴趣,并对特定的b和size值进行了一些计算,以得到以下序列:
rslt = [[0+4,7],[7+2,16],[16+4,27]]这是[b[i]+size[i],b[i+1]]的重复。
发布于 2019-12-24 10:20:03
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}}"发布于 2019-12-24 10:36:02
我会这样做:
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}}"
发布于 2019-12-30 11:12:04
你可以试试这个:
from difflib import *
orig = "1234567890"
commented = "123435456353453578901343154"
diff = SequenceMatcher(None, orig, commented)
a, b, size = zip(*diff.get_matching_blocks())
start = {x + y : '{{' for x, y in zip(b[:-1],size)}
end = dict.fromkeys(b[1:], '}}')
rslt = {**start, **end}
final_str = ''.join(rslt.get(ix,'') + n for ix, n in enumerate(commented)) + '}}'
print(final_str)输出:
'1234{{354}}56{{3534535}}7890{{1343154}}'解释
因为SequenceMatcher().matching_blocks()是可迭代的,所以您可以直接将它解压缩到变量中。
然后创建一个以开始索引作为键的字典,以value.
}},这是rslt.中的两个字典。
然后通过将commented的字符作为默认值传递给dict.get和rslt dict中的索引,形成一个列表,在字符前面加上相应的大括号。最后加入到字符串中。
https://stackoverflow.com/questions/59419950
复制相似问题