【发布时间】:2016-05-12 22:37:02
【问题描述】:
我有一个脚本可以打开和读取文本文件,将每个单词分开并列出这些单词。我做了计数器来计算列表中的每个单词出现了多少次。然后我想在 .csv 文件中导出每一行,如下所示:
单词 hello 出现 10 次
word house 出现 5 次
单词树出现 3 次
...等等
您能告诉我我需要在此处更改哪些内容才能使脚本正常工作吗?
from collections import Counter
import re
import csv
cnt = Counter()
writefile = open('test1.csv', 'wb')
writer = csv.writer(writefile)
with open('screenplay.txt') as file: #Open .txt file with text
text = file.read().lower()
file.close()
text = re.sub('[^a-z\ \']+', " ", text)
words = list(text.split()) #Making list of each word
for word in words:
cnt[word] += 1 #Counting how many times word appear
for key, count in cnt.iteritems():
key = text
writer.writerow([cnt[word]])
【问题讨论】: