我正在尝试解决一个困难的问题,但很迷茫。
这是我的任务:
INPUT: file
OUTPUT: dictionary
Return a dictionary whose keys are all the words in the file (broken by
whitespace). The value for each word is a dictionary containing each word
that can follow the key and a count for the number of times it follows it.
You should lowercase everything.
Use strip and string.punctuation to strip the punctuation from the words.
Example:
>>> #example.txt is a file containing: "The cat chased the dog."
>>> with open('../data/example.txt') as f:
... word_counts(f)
{'the': {'dog': 1, 'cat': 1}, 'chased': {'the': 1}, 'cat': {'chased': 1}}
以下是我目前所做的一切,至少试图提取正确的单词:
以下是我目前为止所做的一切,至少试图提取出正确的单词:
def word_counts(f):
i = 0
orgwordlist = f.split()
for word in orgwordlist:
if i<len(orgwordlist)-1:
print orgwordlist[i]
print orgwordlist[i+1]
with open('../data/example.txt') as f:
word_counts(f)
我想我需要以某种方式使用.count方法,并最终将一些字典进行压缩,但我不确定如何计算每个第一个单词的第二个单词数量。
我知道我离解决问题还有很长的路要走,但是我试图一步步来解决。任何帮助都将不胜感激,甚至只是指向正确方向的提示。
f.split()
。f
是一个文件处理器,不是一个字符串。 - Willem Van Onsem