Created
July 22, 2015 07:39
-
-
Save BastinRobin/04c094f5e8345ac0874d to your computer and use it in GitHub Desktop.
Count the word frequencies of text file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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