在统计文本文档中出现单词时出现问题

我想浏览大量文本文档,并在文章标题和单词出现次数的简单数据框中输出这些文档中特定单词的数量。但是我的输出数据帧显然是不正确的。我怀疑我在用代码做些愚蠢的事情。谁能帮助您确定问题所在?

我使用glob软件包收集文章,然后使用count函数遍历它们。但是,我的输出却给了我明显错误的答案,例如在非常大的文档中出现诸如“ we”之类的简单事物时,计数为“ 1”或“ 0”。

import glob

articles = glob.glob('Test/*.txt')

we_dict = {}

for article in articles:
    we_dict[article] = article.count("we")

we = pd.DataFrame.from_dict(we_dict,orient='index',dtype=None)

没有产生错误消息,因此代码正在执行某些操作-产生了一个数据帧。但是输出的计数值应该是数百个,而不是小数,例如0、1、2。

编辑:

非常有用的回复,适用于将来有相同查询的读者使用的版本。我确定代码可以有所简化。

import glob
import re

articles = glob.glob('Test/*.txt')

we_dict = {}

for article in articles:
    with open(article,'r',encoding="utf8") as art:
        a = art.read()
        a = a.lower()
        we_dict[article] = sum(1 for match in re.finditer(r"\bwe\b",a))

we = pd.DataFrame.from_dict(we_dict,dtype=None)

shuangzai520 回答:在统计文本文档中出现单词时出现问题

现在,您的代码正在遍历文章列表,并声明article作为文件名。 we_dict[article] = article.count("we")行实际上是在使用您的文件名,并试图在名称本身中找到单词“ we”!因此,您需要做的是使用filename打开文件,然后读取各行。

解决此问题的一种可能方法是将所有文件读入词典,然后用单词数来遍历该字典。也许像这样:

import glob
import pandas as pd

articles = glob.glob('*.txt')
txt_files = {}
word = 'cupcakes'

for article in articles:
    with open(article,'r') as file:
        txt_files[article] = file.read().splitlines().count(word)

my_word = pd.DataFrame.from_dict(txt_files,orient='index')
本文链接:https://www.f2er.com/3163476.html

大家都在问