python - 计算给定文本文件中每个单词的出现次数
问题描述
我正在寻找计算我正在使用 os.scandir 读取的一组文件中的每个单词
import string
import os
d = dict()
for filename in os.scandir(directory):
if filename.path.endswith(".txt"):
f = open(filename, encoding = 'utf-8-sig')
lines = f.readlines()
for line in lines:
line = line.strip()
line = line.lower()
line = line.translate(line.maketrans("", "", string.punctuation))
words = line.split(" ")
for word in words:
if word in d:
d[word] = d[word] + 1
else:
count 1
d[word] = 1
for key in list(d.keys()):
print(key, ":", d[key])
问题:这会打印但列出了我不想要的数字,并且由于某种原因没有计算每个单词的真实数量,因为我正在查看的文件实际上非常庞大并且有 500 多个。
上面的结果是 -
operations : 22
: 1
10q : 5
overview : 1
highlights : 1
covid19 : 12
million : 5
2019 : 1
profile : 1
xray : 1
business : 5
consumables : 1
products : 2
35 : 1
response : 5
only : 2
follows : 1
procedures : 5
safely : 1
guidelines : 2
safety : 2
initiatives : 4
includes : 4
restrictions : 4
demand : 9
36 : 1
necessary : 2
operates : 3
2020 : 8
cash : 14
pandemic : 8
requirements : 1
drivers : 4
growth : 11
time : 7
37 : 1
developed : 1
future : 12
statements : 10
currencies : 2
这缺少很多数据,我只是想知道我在哪里绊倒导致这种情况。
任何帮助,将不胜感激。
解决方案
这是一个使用nltk
包的超级简单的方法。
我使用内置的示例文本进行测试和演示。但是,您可以将其包装在一个函数中,并将文件中的原始文本传递给该word_tokenize()
函数,该函数会将原始文本解析为一个列表。然后,将该单词列表传递给FreqDist()
类以计算单词频率分布......或单词计数。
from nltk import corpus, FreqDist, word_tokenize
# Test on the first 50 characters of the Inaugural Address.
text = corpus.inaugural.raw()[:50]
words = word_tokenize(text)
dist = FreqDist(words)
for k, v in dist.items():
print(k, ':', v))
原文:
'Fellow-Citizens of the Senate and of the House of '
输出:
Fellow-Citizens : 1
of : 3
the : 2
Senate : 1
and : 1
House : 1
推荐阅读
- angular - Angular ng 服务命令
- android - 来自同一应用程序的 Firebase (FCM) 分组通知点击
- javascript - 我们可以从 Web 应用程序的前端进行缩小吗?
- eclipse - Eclipse 和 Visual Studio Code 中的量角器自动内容问题
- python - cx_Freeze 的熊猫分析问题
- bash - 从给定日期计算日期
- ruby-on-rails - 使用设计实现两因素身份验证
- oracle - 我怎样才能找到所有没有参考的表
- devexpress - DevExpress XAF:获取子集合的集合
- html - 将绝对定位的 DIV 与 IE11 中 TD 元素内的左值垂直对齐