来自Google Python Class

时间:2016-09-03 18:34:25

标签: python python-2.7

首先,如果前面有一些愚蠢的错误,请道歉:我刚开始(“重新”)学习Python(我使用的是Python 2.7)。

我已经完成了一个名为“模仿”的Google Python类练习,但我有时会得到一些奇怪的结果,我想了解为什么会这样。

练习要求以下事项:

1)读入命令行中指定的文件。

2)构建一个“模仿”字典,将文件中出现的每个单词映射到文件中紧跟该单词的所有单词的列表。单词列表可以是任何顺序,并且应该包括重复。因此,例如,键“和”可能具有列表[“then”,“best”,“then”,“after”,...]列出文本中“and”之后的所有单词。我们会说空字符串是文件中第一个单词之前的字符串。

3)使用模仿dict,发出模仿原始文本的随机文本相当容易。打印一个单词,然后查找下一个可能出现的单词并随机选择一个单词作为下一个工作。使用空字符串作为第一个词来填充东西。 如果我们遇到一个不在字典中的单词,请回到空字符串以保持移动。

这是我的代码:

import random
import sys

def mimic_dict(filename):
  """Returns mimic dict mapping each word to list of words which follow it."""
  d = {}
  with open(filename) as f:
    text = f.read()
    words = text.split()
  i = 0
  for i in range(len(words) - 1):
    if words[i] not in d:
      d[words[i]] = [words[i + 1]]
    else:
      d[words[i]].append(words[i+1])
    i += 1
  d[''] = words[0]
  return d

def print_mimic(d, word):
  """Given mimic dict and start word, prints 200 random words."""
  mimic_text = []
  while len(mimic_text) < 200:
    if word in d:
      next_word = random.choice(d[word])
      mimic_text.append(next_word)
      word = next_word
    else:
      word = ''
  print ' '.join(mimic_text)

# Provided main(), calls mimic_dict() and mimic()
def main():
  if len(sys.argv) != 2:
    print 'usage: ./mimic.py file-to-read'
    sys.exit(1)

  dict = mimic_dict(sys.argv[1])
  print_mimic(dict, '')

if __name__ == '__main__':
  main()

现在,问题在于,如果我使用一个非常简单的文本文件small.txt来提供此模拟函数,其中包含以下内容:

We are not what we should be
We are not what we need to be
But at least we are not what we used to be
  -- Football Coach

输出如下:

e W e W W W W W e e e e e W e W [...]

即,第一个单词的字母的随机序列。

但是,如果我在一个更长的文件(alice.txt上运行它,其中包含来自爱丽丝梦游仙境的全文),我会在开头有一些随机字母(有时甚至不是那些字母),但是然后它以某种方式起作用,这里有一些例子:

运行1输出(截断):

l i ' s l e ' ' i ' e s e c s ' A large flower-pot that the next[...]

运行2输出(截断):

i i i A little door, staring at all,' said in fact, [...]

运行3输出(截断):

 A Caucus-Race and she found out of Hearts,[...]

似乎一旦它到达字母“A”就会按预期开始工作,但在收到那封信之前我真的无法理解发生了什么。 我确信在某个地方只有一个愚蠢的错误,但是我找不到它,如果一个温柔的灵魂需要一些时间来帮助我理解这里发生的事情,我会非常感激。

非常感谢!

1 个答案:

答案 0 :(得分:1)

你错过了两个角色。

d[''] = words[0]应为d[''] = [words[0]]