计算文本文件中每个单词的频率,并使用python将其存储在变量中

2024-04-26 18:19:30 发布

您现在位置:Python中文网/ 问答频道 /正文

但是没有内置的计数器功能的帮助

将open(r“C:\Users\muizv\Desktop\alice_in_wonderland.txt”、“rt”)作为f:


1条回答
网友
1楼 · 发布于 2024-04-26 18:19:30

您可以读取文件的内容:content = f.read(),然后使用regex查找所有单词words = re.findall(r'[a-zA-Z]+', content),然后在列表上循环并使用dict计数单词:

freq = {}
for word in words:
    freq[word] = freq.get(word, 0) + 1 # adds 1 to the freq of the current word, with 0 as the default
console.log(freq)

相关问题 更多 >