【问题标题】:How do I write array of word count to a csv file?如何将字数数组写入 csv 文件?
【发布时间】:2020-03-24 07:51:48
【问题描述】:

我写了一个代码,计算所有文本单词和出现次数,输出为:

doctype 1
html 3
dir 1
rtl 5
lang 1
head 17

我想将此输出以 word 和 count 逗号分隔的格式写入 csv 文件。

# Open the file in read mode 
text = open("output.txt", "r") 

# Create an empty dictionary 
d = dict() 

# Loop through each line of the file 
for line in text: 
    # Remove the leading spaces and newline character 
    line = line.strip() 

    # Convert the characters in line to  
    # lowercase to avoid case mismatch 
    line = line.lower() 

    # Split the line into words 
    words = line.split(" ") 

    # Iterate over each word in line 
    for word in words: 
        # Check if the word is already in dictionary 
        if word in d: 
            # Increment count of word by 1 
            d[word] = d[word] + 1
        else: 
            # Add the word to dictionary with count 1 
            d[word] = 1

# Print the contents of dictionary 

for key in list(d.keys()): 
    print ( key, ":", d[key]) 

【问题讨论】:

标签: python csv


【解决方案1】:

试试:

with open('my_csv_file.csv','w') as writer:
    for key, val in d.items():
        writer.write("{},{}\n".format(key,val)

这会将字典以“key,val”格式写入输出文件

【讨论】:

    猜你喜欢
    • 2020-05-10
    • 1970-01-01
    • 2014-08-30
    • 2017-06-27
    • 2012-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-03
    相关资源
    最近更新 更多