【问题标题】:Exporting Python Counter to .CSV file将 Python 计数器导出到 .CSV 文件
【发布时间】: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]]) 

【问题讨论】:

    标签: python csv io counter


    【解决方案1】:

    最大的问题是,每个单词的每次出现都会发生第二个 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
    

    【讨论】:

    • 谢谢!它有效,我的代码杂乱无章,所以我忘了检查第二个循环。
    猜你喜欢
    • 2016-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多