gpt4 book ai didi

python - 解包 SequenceMatcher 循环结果

转载 作者:行者123 更新时间:2023-11-30 21:54:06 26 4
gpt4 key购买 nike

在 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]]的重复。

最佳答案

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

Python 内置函数 zip 的引用:https://docs.python.org/3/library/functions.html#zip

2。用 "{{""}}"

标记注释

您可以循环遍历 rslt,然后很好地附加 match-so-far 并标记出注释。

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}}"

关于python - 解包 SequenceMatcher 循环结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59419950/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com