Skip to content

Instantly share code, notes, and snippets.

@AO8
Last active June 26, 2018 16:51
Show Gist options
  • Select an option

  • Save AO8/c0b6e6f44ec3833da280d007cdd40a90 to your computer and use it in GitHub Desktop.

Select an option

Save AO8/c0b6e6f44ec3833da280d007cdd40a90 to your computer and use it in GitHub Desktop.
Another (more concise, more Pythonic) frequency word counter using collections.Counter.
# collections.Counter docs at:
# https://docs.python.org/3/library/collections.html#collections.Counter
from collections import Counter
import re
with open("txt_file.txt", "r") as f:
words = re.findall(r"\w+", f.read().lower())
totals = Counter(words).most_common(50) # returns a list of tuples for the 50 most common words and their counts
for word in totals:
print(word[0], "=", word[1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment