Although I usually like to write clean and well documented code, this problem has so many good solutions that I decided to write something in as few lines as I could manage.
I'm still convinced that I can manage something in one line instead of the current three, but I'm giving up for now:
def word_count(fname):
result = {}
map(lambda a:result.__setitem__(a, result.setdefault(a, 0)+1), open(fname).read().split())
return "\n".join(map(lambda row: row[0]+","+str(row[1]), sorted(result.items(), key=lambda a:a[1], reverse=True)[:10]))
print word_count("test_file.txt")
test_file.txt
$ cat test_file.txt
this is
some
random file
is is is
Result:
$ python wordcount.py
is,4
this,1
random,1
some,1
file,1
Edit: Got it as a oneliner, here goes:
def word_count(fname):
return map(lambda a: sorted([(a.count(word), word) for word in set(a)], reverse=True), [open(fname).read().split()])[0][:10]
Quite a few hacks to get this to work, and it's not at all efficient(goes over the whole file for every word, so it's O(n^2) where n is the number of words) but it works and it's one line.
Note that the map is there to be able to assign a value(in this case "a") to "open(fname).read().split()" so I don't have to read the file multiple times(I'm using it as the equivalent of a "let" essentially but python doesn't have that)