我正在尝试编写一段代码来统计包含大约10000个文件的文档中单词出现的频率,但我得到的不是总频率,而是最后一个文件的单词计数,因为它将覆盖前一次迭代。到目前为止我的代码是:
import csv
import glob
import re
def main():
file_list = glob.glob(TARGET_FILES)
for file in file_list:
with open(file, 'r', encoding='UTF-8', errors='ignore') as f_in:
doc = f_in.read()
def get_data(doc):
vdictionary = {}
w = csv.writer(open("output1.csv", "w",newline=''))
tokens = re.findall('\w+', doc)
for token in tokens:
if token not in vdictionary:
vdictionary[token] = 1
else:
vdictionary[token] += 1
for key, val in vdictionary.items():
w.writerow([key, val])发布于 2018-03-26 06:01:18
我认为问题在于每次迭代都会清空csv文件。如果使用以下命令会发生什么:
w = csv.writer(open("output1.csv", "a",newline=''))而不是
w = csv.writer(open("output1.csv", "w",newline=''))?我想你会得到每个文件的计数。如果是这样的话,您应该创建一个字典,为每个文件更新它,并仅在最后将其写入csv文件。
你可以得到一个这样的字典:
def get_data(doc, vdictionary):
tokens = re.findall('\w+', doc)
for token in tokens:
if token not in vdictionary:
vdictionary[token] = 1
else:
vdictionary[token] += 1
return vdictionary
def main():
files = {get your files}
vdictionary = {}
for file in files:
vdictionary = get_data(file, vdictionary)
w = csv.writer(open("output1.csv", "w",newline=''))
for key, val in vdictionary.items():
w.writerow([key, val])发布于 2018-03-26 06:01:32
我认为您的问题是,每次调用get_data时,您只使用该文件中的计数重写csv (我认为)。相反,也许您可以创建一个字典,然后遍历并计算所有文件的每个文件中每个单词的数量,然后输出到w.writerow([key, val])。
本质上,不要在每次浏览文件时都输出到csv。浏览所有文件,更新一个主字典,然后输出到csv。
https://stackoverflow.com/questions/49481344
复制相似问题