Skip to content

Instantly share code, notes, and snippets.

@BastinRobin
Created July 22, 2015 07:39
Show Gist options
  • Select an option

  • Save BastinRobin/04c094f5e8345ac0874d to your computer and use it in GitHub Desktop.

Select an option

Save BastinRobin/04c094f5e8345ac0874d to your computer and use it in GitHub Desktop.
Count the word frequencies of text file
import csv
data = open('data.txt', 'r')
for line in data.readlines():
tokens = line.split()
# iterate througt the list
# count the existence
d = {}
for word in tokens:
if word in d:
d[word] = d[word] + 1
else:
d[word] = 1
with open('mycsvfile.csv', 'wb') as f: # Just use 'w' mode in 3.x
w = csv.DictWriter(f, d.keys())
w.writerow(d)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment