Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
297 views
in Technique[技术] by (71.8m points)

Python - difference between two strings

I'd like to store a lot of words in a list. Many of these words are very similar. For example I have word afrykanerskoj?zyczny and many of words like afrykanerskoj?zycznym, afrykanerskoj?zyczni, nieafrykanerskoj?zyczni. What is the effective (fast and giving small diff size) solution to find difference between two strings and restore second string from the first one and diff?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use ndiff in the difflib module to do this. It has all the information necessary to convert one string into another string.

A simple example:

import difflib

cases=[('afrykanerskoj?zyczny', 'afrykanerskoj?zycznym'),
       ('afrykanerskoj?zyczni', 'nieafrykanerskoj?zyczni'),
       ('afrykanerskoj?zycznym', 'afrykanerskoj?zyczny'),
       ('nieafrykanerskoj?zyczni', 'afrykanerskoj?zyczni'),
       ('nieafrynerskoj?zyczni', 'afrykanerskojzyczni'),
       ('abcdefg','xac')] 

for a,b in cases:     
    print('{} => {}'.format(a,b))  
    for i,s in enumerate(difflib.ndiff(a, b)):
        if s[0]==' ': continue
        elif s[0]=='-':
            print(u'Delete "{}" from position {}'.format(s[-1],i))
        elif s[0]=='+':
            print(u'Add "{}" to position {}'.format(s[-1],i))    
    print()      

prints:

afrykanerskoj?zyczny => afrykanerskoj?zycznym
Add "m" to position 20

afrykanerskoj?zyczni => nieafrykanerskoj?zyczni
Add "n" to position 0
Add "i" to position 1
Add "e" to position 2

afrykanerskoj?zycznym => afrykanerskoj?zyczny
Delete "m" from position 20

nieafrykanerskoj?zyczni => afrykanerskoj?zyczni
Delete "n" from position 0
Delete "i" from position 1
Delete "e" from position 2

nieafrynerskoj?zyczni => afrykanerskojzyczni
Delete "n" from position 0
Delete "i" from position 1
Delete "e" from position 2
Add "k" to position 7
Add "a" to position 8
Delete "?" from position 16

abcdefg => xac
Add "x" to position 0
Delete "b" from position 2
Delete "d" from position 4
Delete "e" from position 5
Delete "f" from position 6
Delete "g" from position 7

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...