Search code examples
pythoncsvmultiple-columns

How do I write words and their frequencies into two separate columns in CSV file


I have the desired input (a Counter object, from my previous question), which looks like this:

 (u'twice', 4302),

 (u'thru', 4286),

 (u'mailing', 4276),

 (u'specifically', 4274),

etc.

Now, I am trying to write the words and their frequency values into a CSV file. I tried the following code below, which I got from a similar question on this site:

with open("fiancee_wordfreq.csv" , "wb") as f:
     writer = csv.writer(f)  
     for val in cn:
         writer.writerow([val])

When I open the CSV file in Excel, I find that only the words but not their frequencies. So, "specifically" is one of the words listed in column A, but not 4274. I would like to have the word in column A and the frequency in column B, but I can't get the frequency to show up at all.


Solution

  • Iterating through a Counter is like iterating through a dictionary - you only get the keys. writerow() requires a sequence, so val isn't enough, but wrapping it in brackets to make a list with [val] just allows you to write that key as a single column. Use the items() method to get a key as well as its associated value:

    with open("fiancee_wordfreq.csv" , "wb") as f:
         writer = csv.writer(f)  
         for pair in cn.items():
             writer.writerow(pair)
    

    Or use each key to index the Counter:

    with open("fiancee_wordfreq.csv" , "wb") as f:
         writer = csv.writer(f)  
         for val in cn:
             writer.writerow([val, cn[val]])