python - 将 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.
解决方案
这是因为您正在重置word
. 尝试:
for i in range(5):
next_word = random.choice(bigrams[word])
print(word, next_word)
word = next_word
推荐阅读
- excel - 更换方法和改变格式?
- java - 如何使用 SAX 在 1 个班级一次解析 2 个 xml 文件
- z3 - SMT 上下文中的“无量词逻辑”是什么意思?
- python - 如何使用 hidden_markov 修复广播状态和发射概率的错误?
- python - 尝试使用棉花糖通过 data_key 加载数据时出现“缺少数据”
- .net - vb.net“传递给 C 运行时函数的无效参数”
- python - Pandas read_csv 错误标记来自 Gutenberg 项目的文本
- html - 如何用 rgba 覆盖父元素并覆盖子图像
- javascript - Vuejs:为什么我的数组结果包含__ob__:观察者?
- c# - 为什么加载区域控制器时我的 BaseController.User 值 == null?