Skip to content

Instantly share code, notes, and snippets.

@akoskadar
Created November 7, 2013 17:42
Show Gist options
  • Save akoskadar/7358703 to your computer and use it in GitHub Desktop.
Save akoskadar/7358703 to your computer and use it in GitHub Desktop.
This piece of Pyhton code counts the number of times words occur in a text file, and writes the result in a separate text file.
import string
fil = open('C:\\Python27\\elo.txt' , "r")
new_file = open('C:\Python27\\freq_list.txt', 'w')
text = fil.read()
fil.close()
textClean = ''
for i in text:
if i.isalpha() or i.isspace():
textClean+=i
textLow = string.lower(textClean)
textVar = textLow.split()
newText = ''
for w in textVar:
w += ' '
if w not in newText:
newText += w
newText = string.split(newText)
freq_list = ''
for w in newText:
wordCount = textVar.count(w)
freq_list = freq_list + w + ',' + str(wordCount) + '\n'
new_file.write(freq_list)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment