Finding differences between strings

前端 未结 3 848
礼貌的吻别
礼貌的吻别 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:21

    You could use difflib, and do it like this:

    from difflib import Differ
    
    def appendBoldChanges(s1, s2):
        "Adds  tags to words that are changed"
        l1 = s1.split(' ')
        l2 = s2.split(' ')
        dif = list(Differ().compare(l1, l2))
        return " ".join([''+i[2:]+'' if i[:1] == '+' else i[2:] for i in dif 
                                                               if not i[:1] in '-?'])
    
    print appendBoldChanges("britney spirs", "britney sprears")
    print appendBoldChanges("sora iro days", "sorairo days")
    #Output:
    britney sprears
    sorairo days
    

提交回复
热议问题