【问题标题】:update word1 to be the last word generated将 word1 更新为生成的最后一个单词
【发布时间】:2020-05-17 11:20:54
【问题描述】:

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

我想向用户询问 bigram 字典/列表中的一个词(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


    【解决方案1】:

    这是因为您要重置word 的值。试试:

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

    【讨论】:

    • 谢谢。我是编程新手,还在学习中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-29
    • 2021-11-29
    • 1970-01-01
    • 2016-06-20
    • 2010-12-04
    • 2019-01-11
    相关资源
    最近更新 更多