[英]Merge two multiline strings like git does
我想“组合”两个(通常非常相似)多行字符串(接近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
等的手动方法。 但我需要一种方法来保持order 、相似的部分和多次出现的相同(即空)行。
有没有一种“pythonic”(简短、优雅、复杂)的方式来做到这一点?
如果您只有两个元素(列表),这应该有效:
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("?"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.