Finding differences between strings

前端 未结 3 958
礼貌的吻别
礼貌的吻别 2021-02-03 14:36

I have the following function that gets a source and a modified strings, and bolds the changed words in it.

def appendBoldChanges(s1, s2):
    \"Adds &l         


        
3条回答
  •  滥情空心
    2021-02-03 15:18

    A small upgrade tp @fraxel answer that returns 2 outputs - the original and the new version with marked changes. I also change the one-liner to a more readable version in my opinion

    def show_diff(text, n_text):
        seqm = difflib.SequenceMatcher(None, text, n_text)
        output_orig = []
        output_new = []
        for opcode, a0, a1, b0, b1 in seqm.get_opcodes():
            orig_seq = seqm.a[a0:a1]
            new_seq = seqm.b[b0:b1]
            if opcode == 'equal':
                output_orig.append(orig_seq)
                output_new.append(orig_seq)
            elif opcode == 'insert':
                output_new.append("{}".format(new_seq))
            elif opcode == 'delete':
                output_orig.append("{}".format(orig_seq))
            elif opcode == 'replace':
                output_new.append("{}".format(new_seq))
                output_orig.append("{}".format(orig_seq))
            else:
                print('Error')
        return ''.join(output_orig), ''.join(output_new)
    

提交回复
热议问题