Skip to content

Instantly share code, notes, and snippets.

@cessor
Created April 30, 2014 10:38
Show Gist options
  • Select an option

  • Save cessor/1b070448f910cc8ee186 to your computer and use it in GitHub Desktop.

Select an option

Save cessor/1b070448f910cc8ee186 to your computer and use it in GitHub Desktop.
import operator
def countWords(fileName):
mydict = {}
fobj = open(fileName, 'r')
for line in fobj:
zuordnung = line.split()
for word in zuordnung:
if mydict.has_key(word):
mydict[word] = mydict.get(word)+1
else:
mydict[word] = 1
fobj.close()
wordList = mydict.items()
wordList = sorted(wordList, key=operator.itemgetter(1), reverse=True)
for word in wordList:
anzahl,word = word
print '%s -> %s' % (word,anzahl)
# Oder doch lieber...
def countWords(fileName):
with open(filename,'r') as f:
text = f.read().split()
words = Counter(text)
for anzahl, word in words.most_common():
print '%s -> %s' % (word, anzahl)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment