Created
October 18, 2015 17:40
-
-
Save andyinabox/70dd4dc7e351279a1971 to your computer and use it in GitHub Desktop.
Word count example
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
import sys | |
# set our count variable as an empty dict | |
count = {} | |
# iterate through lines of input | |
for line in sys.stdin: | |
# strip whitespace and line breaks | |
line = line.strip() | |
# break into a list of words (break apart at spaces) | |
words = line.split() | |
# now iterate through our words | |
for word in words: | |
# if the word has already been added to the dict | |
# then add 1 to the stored value | |
if word in count: | |
count[word] += 1 | |
# otherwise, add the word to the dict with value of 1 | |
else: | |
count[word] = 1 | |
# now iterate through a sorted list of the dict's keys | |
for word in sorted(count.keys()): | |
# now print the word and it's value in alpha order | |
print word, str(count[word]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment