I have list of lists as follows.
mycookbook= [["i", "love", "tim", "tam", "and", "chocolate", "ice", "cream"], ["cooking",
"fresh", "vegetables", "is", "easy"], ["fresh", "vegetables", "and", "fruits", "are", "good",
"for", "health"]]
I also have a list as follows.
mylist = ["tim tam", "chocolate ice cream", "fresh vegetables and fruits"]
Now, I want to find the consecutive words in mylist
and combine them as follows to update mycookbook
.
mycookbook = [["i", "love", "tim tam" "and", "chocolate ice cream"], ["cooking", "fresh vegetables",
"is", "easy"],["fresh vegetables and fruits", "are", "good", "for", "health"]]
I am currently using two words as follows.
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)
You need nested loops, one for the starting index of a phrase, the next for the ending index. You can then use a list slice to get all the words in between.
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
We can't use for i in range(len(sentence))
because the length of sentence
changes whenever we replace a slice with the phrase.
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加