作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我正在尝试解决一个难题,但迷路了。
这是我应该做的:
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 方法并最终将一些词典压缩在一起,但我不确定如何计算每个第一个单词的第二个单词。
我知道我离解决问题还差得很远,但我正在努力一步一个脚印。感谢任何帮助,即使只是指向正确方向的提示。
最佳答案
我们可以通过两次解决这个问题:
Counter
并使用zip(..)
计算两个连续单词的元组;和Counter
放入字典中。这导致以下代码:
from collections import Counter, defaultdict
def word_counts(f):
st = f.read().lower().split()
ctr = Counter(zip(st,st[1:]))
dc = defaultdict(dict)
for (k1,k2),v in ctr.items():
dc[k1][k2] = v
return dict(dc)
关于python - 为文件中的每个单词创建字典并计算其后单词的频率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44729412/
我是一名优秀的程序员,十分优秀!