我在Python中运行了下面的代码,从文本文件中生成单词列表及其计数。我将如何过滤掉我的" frequency_list"只有1的变量?
此外,如何将底部的print语句循环导出为CSV
提前感谢您提供的任何帮助。
import re
import string
frequency = {}
document_text = open('Words.txt', 'r')
text_string = document_text.read().lower()
match_pattern = re.findall(r'\b[a-z]{3,15}\b', text_string)
for word in match_pattern:
count = frequency.get(word,0)
frequency[word] = count + 1
frequency_list = frequency.keys()
for words in frequency_list:
print (words, frequency[words])
答案 0 :(得分:1)
对于第一部分 - 你可以使用dict理解:
frequency = {k:v for k,v in frequency.items() if v>1}
答案 1 :(得分:1)
要过滤单词,另一种方法是:
frequency = dict(filter(lambda (k,v): v>1, frequency.items()))
要将底部的print语句循环导出为CSV,您可以这样做:
import csv
frequency_list = ['word1','word2','word3'] # example
with open('output.csv','w') as csvfile:
writer = csv.writer(csvfile, delimiter=",")
writer.writerow(frequency_list)
这将生成一个" output.csv'文件中包含一行中的frequency_list中的字词。
要为每个单词获取一行,请尝试以下操作:
with open('output.csv','w') as csvfile:
writer = csv.writer(csvfile, delimiter=",")
writer.writerows([i.strip() for i in l.split(',')] for l in frequency_list)
更新
要使用计数器获取csv,请保留初始字典并执行以下操作:
frequency = {"one":1,"two":2,"three":3} #example
with open('output.csv', 'w') as csvfile:
writer = csv.writer(csvfile)
for key, value in frequency.items():
writer.writerow([key, value])