Last active
June 20, 2018 09:31
-
-
Save jflanaga/3af92dc75c2742893e0dae88bbfa54e8 to your computer and use it in GitHub Desktop.
Count the number of words in a string
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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