首页 > 解决方案 > 计算给定文本文件中每个单词的出现次数

问题描述

我正在寻找计算我正在使用 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

这缺少很多数据,我只是想知道我在哪里绊倒导致这种情况。

任何帮助,将不胜感激。

标签: python

解决方案


这是一个使用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

推荐阅读