dedtech.info

Information about computer technology.

Export A Counter Object To A CSV File With Python

This blog post will explain how to export a counter object to a csv file with Python.

The required libraries need to be imported.

from collections import Counter
from nltk.corpus import brown
import csv

The variable words are set to the word and tag pairs from the Brown corpus.

words = brown.tagged_words(tagset="universal")

After that, the variable words are set to a list comprehension that lowercases each word and builds a list of word and tag pairs.

words = [(word.lower(), tag) for word, tag in words]

The variable pairs are set to a Counter object that uses the previously built list. The counter function processes the list, and frequencies are generated for each word and tag pair.

pairs = Counter(words)

The statements below will open a file named frequency.csv in write mode. There will be a header added to the csv file first. Then the word and tag pairs with their frequencies will be added to the csv file.

with open("frequency.csv", mode='w', newline='', encoding='utf-8') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow(["item", "count"])
    for item, count in pairs.items():
        writer.writerow([item, count])

This is what the whole source code looks like.

from collections import Counter
from nltk.corpus import brown
import csv

words = brown.tagged_words(tagset="universal")
words = [(word.lower(), tag) for word, tag in words]

pairs = Counter(words)
    
with open("frequency.csv", mode='w', newline='', encoding='utf-8') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow(["item", "count"])
    for item, count in pairs.items():
        writer.writerow([item, count])

Leave a Reply

Your email address will not be published. Required fields are marked *