我一直在编写Python代码,以使用Python列表(word_list
中包含的单词来查找文本文档中单词的频率分布。该程序计算出频率分布,然后将其打印到屏幕上,但是,当我尝试将频率分布写入.csv文件时,尽管目录中有许多文本文件,但它只会重复写入FreqDist
的最后一行。我的代码如下
CIK_List = []
for filename in glob.glob(os.path.join(test_path, '*.txt')):
CIK = re.search(r"\_([0-9]+)\_", filename) # extract the CIK from the filename
path = nltk.data.find(filename)
raw = open(path, 'r').read()
tokens = word_tokenize(raw)
words = [h.lower() for h in tokens]
f_dist = nltk.FreqDist([s.lower() for s in words])
print(f_dist)
wordcount = collections.Counter()
CIK_List.append(CIK)
with open(file_path, 'w+', newline= '') as csv_file:
writer = csv.writer(csv_file)
writer.writerow(["CIK"] + word_list)
for m in word_list:
print([CIK.group(1)], [f_dist[m]], end='')
for val in CIK_List:
writer.writerows(([val.group(1)] + [f_dist[m] for m in word_list],))
答案 0 :(得分:1)
问题在于,对于您阅读的每个输入文件,您都会创建输出文件并写入
在代码末尾看下面的循环。它是做什么的?
for val in CIK_List:
writer.writerows(([val.group(1)] + [f_dist[m] for m in word_list],))
CIK_List
是一个正则表达式匹配项的列表。对于每个这样的正则表达式匹配,我们写出第一个匹配组(这是文件名的数字部分),然后写出不依赖val
的东西。因此,val
在正则表达式匹配列表中运行时,您一次又一次获得相同的输出。
您还将打开文件几次,每个输入文件一次,并且每次打开文件时,您都会丢弃以前的内容。
您可能想要做的是打开输出文件一次,写出标题行,然后针对每个输入文件,根据该输入文件的内容向输出文件写一行:>
CIK_List = []
with open(file_path, 'w+', newline= '') as csv_file:
writer = csv.writer(csv_file)
writer.writerow(["CIK"] + word_list)
for filename in glob.glob(os.path.join(test_path, '*.txt')):
CIK = re.search(r"\_([0-9]+)\_", filename) # extract the CIK from the filename
path = nltk.data.find(filename)
raw = open(path, 'r').read()
tokens = word_tokenize(raw)
words = [h.lower() for h in tokens]
f_dist = nltk.FreqDist([s.lower() for s in words])
print(f_dist)
wordcount = collections.Counter()
CIK_List.append(CIK)
for m in word_list:
print([CIK.group(1)], [f_dist[m]], end='')
writer.writerow([CIK.group(1)] + [f_dist[m] for m in word_list])