Word frequency: Difference between revisions

→‎{{header|Python}}: Add less terse Python3.6 version (f-strings!)
(Adds word count task)
 
(→‎{{header|Python}}: Add less terse Python3.6 version (f-strings!))
Line 40:
 
=={{header|Python}}==
===Python2.7===
<lang python>import collections
import re
Line 58 ⟶ 59:
('in', 11204), ('he', 9645), ('was', 8619), ('that', 7922), ('it', 6659)]
</pre>
 
===Python3.6===
<lang python>from collections import Counter
from re import findall
 
les_mis_file = 'les_mis_135-0.txt'
 
def _count_words(fname):
with open(fname) as f:
text = f.read()
words = findall(r'\w+', text.lower())
return Counter(words)
 
def most_common_words_in_file(fname, n):
counts = _count_words(fname)
for word, count in [['WORD', 'COUNT']] + counts.most_common(n):
print(f'{word:>10} {count:>6}')
 
 
if __name__ == "__main__":
n = int(input('How many?: '))
most_common_words_in_file(les_mis_file, n)</lang>
 
{{Out}}
<pre>How many?: 10
WORD COUNT
the 41036
of 19946
and 14940
a 14586
to 13939
in 11204
he 9645
was 8619
that 7922
it 6659</pre>
 
=={{header|UNIX Shell}}==
Anonymous user