[英]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.