如何在python中删除两个字符串之间的重复单词?

如何在python中删除两个字符串之间的重复单词?,python,string,Python,String,我在一个OCR项目中工作。经过一些操作后,我有两个类似的字符串: s1 = "This text is a test of" s2 = "a test of the reading device" ns2 = "the reading device" sf= "This text is a test of the reading device" 我想知道如何删除第二个字符串中的重复单词。我的想法是找到每个列表中重复的单词的位置。我试过这个: e1 = [x for x in s1.s

我在一个OCR项目中工作。经过一些操作后,我有两个类似的字符串:

s1 = "This text is a test of"
s2 = "a test of the reading device"
ns2 = "the reading device"    
sf= "This text is a test of the reading device"
我想知道如何删除第二个字符串中的重复单词。我的想法是找到每个列表中重复的单词的位置。我试过这个:

e1 = [x for x in s1.split()]
e2 = [y for y in s2.split()]

for i, item2 in enumerate(e2):
    if item2 in e1:
        print i, item2 #repeated word and index in the first string
        print e1.index(item2) #index in the second string
现在我有了重复的单词以及它们在第一个和第二个列表中的位置。如果它们的顺序相同,我需要它来逐字比较。这是因为同一个单词可能在字符串中出现两次或更多次(将来的验证)

最后,我想要一个这样的字符串:

s1 = "This text is a test of"
s2 = "a test of the reading device"
ns2 = "the reading device"    
sf= "This text is a test of the reading device"

我正在Windows 7上使用python 2.7。

这里是另一个尝试

from difflib import SequenceMatcher as sq
match = sq(None, s1, s2).find_longest_match(0, len(s1), 0, len(s2))
结果

print s1 + s2[match.b+match.size:]
本文是对阅读设备的测试


这是另一种尝试,

from difflib import SequenceMatcher as sq
match = sq(None, s1, s2).find_longest_match(0, len(s1), 0, len(s2))
结果

print s1 + s2[match.b+match.size:]
本文是对阅读设备的测试

也许是这个?
''.join([x代表s1中的x.split(''))+[y代表s2中的y.split(''),如果y不在s1.split(''))
我没有仔细测试过它,但这可能是处理此类需求的一个好主意。

可能是这个吗?
''.join([x代表s1中的x.split(''))+[y代表s2中的y.split(''),如果y不在s1.split(''))

我没有仔细测试它,但这可能是处理此类需求的一个好主意。

已有文档。请用它。使用
e1.index(item2)
找出item2在e1文档中的位置。请用它。使用
e1.index(item2)
找出item2在e1中的位置。它将删除第二个字符串中所有出现的单词。它不会只删除第一个字符串中已经存在的单词吗?
s1='hi are you there'
s2='you there hi for'
尝试这些输入,对你来说是有意义的。正如@RahulKP所说的。当同一个单词在字符串中出现两次或两次以上时,它将不起作用。它将删除第二个字符串中出现的所有单词。它不会只删除第一个字符串中已经存在的单词吗?
s1='hi are you there'
s2='you there hi for'
尝试这些输入,对你来说是有意义的。正如@RahulKP所说的。当同一个单词在字符串中出现两次或两次以上时,它就不起作用了。它工作得很好,但是如果我有类似的东西,会发生什么呢。我希望你能帮助我!它工作得很好,但是如果我有类似的东西会发生什么呢。我希望你能帮助我!