Skip to content

Instantly share code, notes, and snippets.

@jflanaga
Last active June 20, 2018 09:31
Show Gist options
  • Save jflanaga/3af92dc75c2742893e0dae88bbfa54e8 to your computer and use it in GitHub Desktop.
Save jflanaga/3af92dc75c2742893e0dae88bbfa54e8 to your computer and use it in GitHub Desktop.
Count the number of words in a string
# Method 1
from collections import defaultdict
def count_words(string):
'''count number of times each word apppears in a string'''
counts = defaultdict(int)
for word in string.split():
counts[word] += 1
return counts
# Method 2
from collections import Counter
def count_words(string):
'''Count number of times each word appears in a string'''
counts = Counter(string.split())
return counts
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment