首先,如果前面有一些愚蠢的错误,很抱歉:我刚刚开始(“重新”)学习Python (我正在使用Python2.7)。
我已经完成了Google Python Class中的一个练习,名为"mimic",但我有时会得到一些奇怪的结果,我想知道为什么会发生这种情况。
该练习要求执行以下操作:
1)读入命令行中指定的文件。
2)建立一个“模拟”字典,将文件中出现的每个单词映射到文件中紧跟在该单词后面的所有单词的列表。单词列表可以是任何顺序,并且应该包含重复的单词。例如,键"and“可能包含列表"then”、"best“、"then”、"after“、...列出课文中"and“后面的所有单词。我们假设空字符串出现在文件中第一个单词之前。
3)使用模仿字典,很容易发出模仿原文的随机文本。打印一个单词,然后查找下一个可能出现的单词,并随机选择一个作为下一个作品。使用空字符串作为启动的第一个单词。如果我们遇到字典中没有的单词,请返回到空字符串以使事情继续进行。
这是我的代码:
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“,它就会像预期的那样工作,但在到达那个字母之前,我真的不能理解发生了什么。我确信在某个地方有一个愚蠢的bug,但我找不到它,如果某个仁慈的人能花点时间帮助我理解这里发生的事情,我将非常感激。
非常感谢!
发布于 2016-09-04 03:00:29
你漏掉了两个字符。
d[''] = words[0]应为d[''] = [words[0]]。
https://stackoverflow.com/questions/39310164
复制相似问题