合并两个重叠的句子

2024-10-05 14:28:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我想合并成两个句子,比如:

sent1 = 'abcdefghiklmn'
sent2 = 'ziklmopqrst'

两个句子有相同的iklm

result = 'abcdefghiklmnopqrst'

非常感谢!你知道吗


Tags: result句子sent2sent1abcdefghiklmnopqrstabcdefghiklmniklmziklmopqrst
3条回答

也许这能帮上忙

sent1 = 'abcdefghiklmn'
sent2 = 'ziklmnopqrst'

for i in sent1:
    n = 0
    for f in sent2:
        n += 1
        if i == f:
            result = sent1 + sent2[n:]
            break

print(result)

^{}很方便:

from difflib import SequenceMatcher
match = SequenceMatcher(None, sent1, sent2).find_longest_match(0, len(sent1), 0, len(sent2))
result = sent1[:match.a]+sent2[match.b:]

这可能适用于:

list(set(list("abc")+list("adef")))

输出为:

['a', 'c', 'b', 'e', 'd', 'f']

并将其转换为单个字符串:

"".join(['a', 'c', 'b', 'e', 'd', 'f'])

输出为:

'acbedf'

相关问题 更多 >