像git那样合并两个多行字符串



我想"组合"两个(通常非常相似(多行字符串(类似于git在合并文件更改时所做的操作(。

类似的东西

>>> combine([
'Hello,',
'this is a text hat has been altered on one place',
'while altered differently on another',],[
'Hello,',
'this is another text hat has been altered on a different place',
'while altered differently on another',])
['Hello,',
'this is another text hat has been altered on a different place',
'this is a text hat has been altered on one place',
'while altered differently on another',]

我没有足够的信息来进行三向差异,所以我想找到相似之处,并确保不会丢失线条。

我发现了几种使用set等的手动方法。但我需要一种方法来保持顺序相似部分和多次出现相同(即空(行。

有没有一种"蟒蛇式"(短小、优雅、精致(的方法可以做到这一点?

如果只有两个元素(列表(,这应该有效:

def combine(target):
return target[0]+list(x for x in target[1] if x not in target[0])

这会将第一个项目添加到第二个项目中但不在第一个项目中的元素中。

后期编辑:

我没有用过很多difflib,但它给了我正确的结果。

import difflib
def merge_text(text1:str, text2:str) -> str:
return "n".join(
line[2:] for line in difflib.Differ().compare(
text1.split("n"),
text2.split("n")) 
if not line.startswith("?"))

最新更新