我是一个绝对的Python初学者。我正在对希腊语剧本进行文本分析并计算每个单词的单词频率。由于游戏时间很长,我无法看到我的全套数据,它只显示频率最低的单词,因为Python窗口中没有足够的空间。我正在考虑将其转换为.csv文件。我的完整代码如下:如何将字典值转换成csv文件?
#read the file as one string and spit the string into a list of separate words
input = open('Aeschylus.txt', 'r')
text = input.read()
wordlist = text.split()
#read file containing stopwords and split the string into a list of separate words
stopwords = open("stopwords .txt", 'r').read().split()
#remove stopwords
wordsFiltered = []
for w in wordlist:
if w not in stopwords:
wordsFiltered.append(w)
#create dictionary by counting no of occurences of each word in list
wordfreq = [wordsFiltered.count(x) for x in wordsFiltered]
#create word-frequency pairs and create a dictionary
dictionary = dict(zip(wordsFiltered,wordfreq))
#sort by decreasing frequency and print
aux = [(dictionary[word], word) for word in dictionary]
aux.sort()
aux.reverse()
for y in aux: print y
import csv
with open('Aeschylus.csv', 'w') as csvfile:
fieldnames = ['dictionary[word]', 'word']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
writer.writerow({'dictionary[word]': '1', 'word': 'inherited'})
writer.writerow({'dictionary[word]': '1', 'word': 'inheritance'})
writer.writerow({'dictionary[word]': '1', 'word': 'inherit'})
我在网上找到了csv的代码。我希望得到的是从最高频率到最低频率的完整数据列表。现在使用这段代码,python似乎完全忽略了csv部分,只是打印数据,就好像我没有编写csv代码一样。
有关我应该编码以查看预期结果的任何想法?
谢谢。
您需要关闭文件 – DrBwts