如何将字数数组写入csv文件?

时间:2020-03-24 07:51:48

标签: python csv

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

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

我想将此输出以单词和计数逗号分隔的格式写到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]) 

1 个答案:

答案 0 :(得分:0)

尝试:

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

这会将字典以“键,值”格式写入外发文件