首页 > 解决方案 > 将 word1 更新为生成的最后一个单词

问题描述

(在 Python 中)使用由 Green Eggs 和 Ham 构建的二元字典。

我想向用户询问一个二元字典/列表中的单词(word1) 。在第一个循环中,用户输入(Word1)将从字典(word2)的列表中打印出一个随机值,之后的每个循环都会更新,因此 word2 成为我们生成的最后一个单词。

简而言之,向用户询问起始词,然后将新生成的一对词打印 5 次。

这是输出应该做什么的示例:

input: do
do not
not like
like green
green eggs
eggs and

到目前为止,这是我的代码。

import random
bigrams = {'Do': ['you'], 'you': ['like', 'like', 'like', 'like'], 'like': ['green', 
'them,', 'green', 'them', 'them', 'them', 'green', 'them,', 'them', 'them', 'them', 'them', 
'them', 'them', 'green', 'them,'], 'green': ['eggs', 'eggs', 'eggs', 'eggs'], 'eggs': 
['and', 'and', 'and', 'and'], 'and': ['ham?', 'ham.', 'ham.', 'ham.'], 'ham?': ['I'], 'I': 
['do', 'am.', 'do', 'would', 'would', 'do', 'do', 'am.', 'do', 'do', 'do', 'do', 'do', 'do', 
'am.'], 'do': ['not', 'not', 'not', 'not', 'not', 'not', 'not', 'not', 'not', 'not'], 'not': 
['like', 'like', 'like', 'like', 'like', 'like', 'like', 'like', 'like', 'like', 'like', 
'like'], 'them,': ['Sam', 'Sam', 'Sam'], 'Sam': ['I', 'I', 'I'], 'am.': ['I', 'Would'], 
'ham.': ['Would', 'I', 'I'], 'Would': ['you', 'you', 'you'], 'them': ['here', 'here', 
'anywhere.', 'in', 'with', 'in', 'with', 'here', 'anywhere.'], 'here': ['or', 'or', 'or'], 
'or': ['there?', 'there.', 'there.'], 'there?': ['I'], 'would': ['not', 'not'], 'there.': 
['I', 'I'], 'anywhere.': ['I', 'I'], 'in': ['a', 'a'], 'a': ['house?', 'mouse?', 'house.', 
'mouse.'], 'house?': ['Would'], 'with': ['a', 'a'], 'mouse?': ['I'], 'house.': ['I'], 
'mouse.': ['I']}

word = input('Word: ')
for i in range(5):
  word = random.choice(bigrams[word])
  print(word, random.choice(bigrams[word]))

这是当前的输出。

Word: do
not like
like them
them here
here or
or there.

标签: python

解决方案


这是因为您正在重置word. 尝试:

for i in range(5):
  next_word = random.choice(bigrams[word])
  print(word, next_word)
  word = next_word 

推荐阅读