搜索两个连续的单词并在python中组合它们

2024-05-15 04:42:24 发布

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

我有如下清单。在

mycookbook= [["i", "love", "tim", "tam", "and", "ice", "cream"], ["cooking", 
"fresh", "vegetables", "is", "easy"], ["fresh", "vegetables", "are", "good", 
"for", "health"]]

我还有一份清单如下。在

^{pr2}$

现在,我想找到mylist中的连续单词,并将它们组合起来更新mycookbook。在

我目前正在做如下工作。在

for sentence in mycookbook:
    for sub in sentence:
        if sub is (mylist[0].split(" ")[0]):

但是我不确定如何检测下一个单词,因为没有命令next()。请帮帮我。在


Tags: andinforis单词sentencetimcream
3条回答

您需要迭代索引,每次尽可能向前看。所以,像这样:

new_sentence = []
index = 0
while index < len(sentence):
    for word in mylist:
        wordlist = word.split()
        if sentence[index:][:len(wordlist)] == wordlist: # This will take the first `len(wordlist)` elements and see if it's a match
            new_sentence.append(word)
            index += len(wordlist)
            break
    else:
        new_sentence.append(sentence[index])
        index += 1

你可以在这里试试:Try it Online!

您可以循环使用原始mycookbook中的每个句子。然后,对于每个句子,从指针指向第一个单词开始。在

  • 案例1:如果sentence[i] + ' ' + sentence[i+1]不在mylist中,我们只需在新句子中添加{}。

  • 案例2:如果sentence[i] + ' ' + sentence[i+1]mylist中,则将此作为一个单词添加到新句子中,并将指针向前移动2步。

示例如下。在

mycookbook= [["i", "love", "tim", "tam", "and", "ice", "cream"], ["cooking",
"fresh", "vegetables", "is", "easy"], ["fresh", "vegetables", "are", "good",
"for", "health"]]

mylist = ["tim tam", "ice cream", "fresh vegetables"]

mycookbook_new = []
for sentence in mycookbook:
    i = 0
    sentence_new = []
    while i < len(sentence):
        if (i == len(sentence)-1 or sentence[i] + ' ' + sentence[i+1] not in mylist):
            sentence_new.append(sentence[i]) # unchanged
            i += 1
        else:
            sentence_new.append(sentence[i] + ' ' + sentence[i+1])
            i += 2
    mycookbook_new.append(sentence_new)

print(mycookbook_new)
'''
[
  ['i', 'love', 'tim tam', 'and', 'ice cream'], 
  ['cooking', 'fresh vegetables', 'is', 'easy'], 
  ['fresh vegetables', 'are', 'good', 'for', 'health']
]
'''
for sentence in mycookbook:
    i = 0
    while i < len(sentence) - 2:
        for m in mylist:

            words = m.split(' ')
            if sentence[i] == words[0]:
                for j in range(1, len(words)):
                    if sentence[i + 1] != words[j]:
                        break

                    sentence[i] += ' ' + words[j]
                    sentence.pop(i + 1)
        i += 1

相关问题 更多 >

    热门问题