Python在字符串中匹配具有相同索引的单词

2024-09-28 22:28:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个长度相等的字符串,希望匹配索引相同的单词。我也在尝试连续比赛,这是我遇到麻烦的地方。在

例如,我有两条弦

alligned1 = 'I am going to go to some show'
alligned2 = 'I am not going to go the show'

我想要的是得到结果:

^{pr2}$

我目前的代码如下:

keys = []
for x in alligned1.split():
    for i in alligned2.split():
        if x == i:
            keys.append(x)

这给了我:

['I','am','show']

任何指导或帮助将不胜感激。在


Tags: to字符串ingoforshow地方some
3条回答

代码简化如下:

alligned1 = 'I am going to go to some show'
alligned2 = 'I am not going to go the show'

keys = []
for i, word in enumerate(alligned1.split()): 
    if word == alligned2.split()[i]:
        keys.append(word)

然后我们需要跟踪是否匹配了一个单词,让我们用一个标志变量来完成。在

^{pr2}$

Kevin's answer是最好的,也是最合适的。我试着用暴力的方式来做。它看起来不太好,但却很管用,没有任何进口产品

alligned1 = 'I am going to go to some show'.split(' ')
alligned2 = 'I am not going to go the show'.split(' ')
keys = []
temp = [v if v==alligned1[i] else None for i,v in enumerate(alligned2) ]
temp.append(None)
tmpstr = ''
for i in temp:
    if i:
        tmpstr+=i+' '
    else:
        if tmpstr: keys.append(tmpstr)
        tmpstr = ''
keys =  [i.strip() for i in keys]
print keys

输出

^{pr2}$

找到匹配的单词是相当简单的,但是将它们放在相邻的组中是相当困难的。我建议使用groupby。在

import itertools

alligned1 = 'I am going to go to some show'
alligned2 = 'I am not going to go the show'

results = []
word_pairs = zip(alligned1.split(), alligned2.split())
for k, v in itertools.groupby(word_pairs, key = lambda pair: pair[0] == pair[1]):
    if k: 
        words = [pair[0] for pair in v]
        results.append(" ".join(words))

print results

结果:

^{pr2}$

相关问题 更多 >