Skip to main content
 首页 » 编程设计

python之在python中组合多个连续的单词

2024年10月01日7sharpest

我有如下列表。

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

我还有一个列表如下。

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

现在,我想在 mylist 中找到连续的单词,并按如下方式组合它们以更新 mycookbook。

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

我目前使用的两个词如下。

for sentence in mycookbook: 
    i = 0 
    while i < len(sentence) - 1: 
        if sentence[i] + ' ' + sentence[i + 1] in mylist: 
            sentence[i] += ' ' + sentence[i + 1] 
            sentence.pop(i + 1) 
        i += 1 
print(mycookbook) 

请您参考如下方法:

您需要嵌套循环,一个用于短语的起始索引,下一个用于结束索引。然后,您可以使用列表切片来获取其间的所有单词。

for sentence in mycookbook: 
    i = 0 
    while i < len(sentence): 
        for j in range(i + 1, len(sentence)+1): 
            phrase = ' '.join(sentence[i:j]) 
            if phrase in mylist: 
                sentence[i:j] = [phrase] 
                break 
        i += 1 

我们不能使用 for i in range(len(sentence)) 因为每当我们用短语替换切片时 sentence 的长度都会改变。

DEMO