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