将 Python 个计数器导出到 .CSV 文件

Exporting Python Counter to .CSV file

我有打开和读取文本文件的脚本,将每个单词分开并列出这些单词。我制作了 Counter 来计算列表中的每个单词出现了多少次。然后我想在 .csv 文件中导出每一行,如下所示:

你好这个词出现了 10 次

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]]) 

最大的问题是,您的第二个 for 循环是针对每个单词的每次出现而发生的,而不是针对每个独特的单词只发生一次。您需要减少整个循环,以便它在您完成计数后执行。尝试这样的事情:

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:
    text = file.read().lower()
    text = re.sub('[^a-z\ \']+', " ", text)
    words = list(text.split())
    for word in words:
        cnt[word] += 1
    for key, count in cnt.iteritems(): #De-dent this block
        writer.writerow([key,count]) #Output both the key and the count

writefile.close() #Make sure to close your file to guarantee it gets flushed