简体   繁体   中英

Merge two multiline strings like git does

I'd like to 'combine' two (usually very similar) multiline strings (close to, what git does, when it merges changes on files).

Something like

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

I don't have enough information for a three-way-diff so I'd like to find similarities and make sure no lines get lost.

I found several manual approaches using set and so on. But I need a way to keep order , similar sections and multiple occurrences of identical (ie empty) lines.

Is there a 'pythonic' (short, elegant, sophisticated) way to do this?

If you have two elements only(lists), this should work:

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

This adds the first item with elements that are in the second item but not in the first.

Later edit:

I haven't used difflib a lot, but it gives the correct result for me.

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("?"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM