gpt4 book ai didi

python - 为文件中的每个单词创建字典并计算其后单词的频率

转载 作者:太空狗 更新时间:2023-10-29 20:13:26 25 4
gpt4 key购买 nike

我正在尝试解决一个难题,但迷路了。

这是我应该做的:

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 方法并最终将一些词典压缩在一起,但我不确定如何计算每个第一个单词的第二个单词。

我知道我离解决问题还差得很远,但我正在努力一步一个脚印。感谢任何帮助,即使只是指向正确方向的提示。

最佳答案

我们可以通过两次解决这个问题:

  1. 在第一遍中,我们构建了一个Counter 并使用zip(..) 计算两个连续单词的元组;和
  2. 然后我们将那个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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com