Skip to content

Instantly share code, notes, and snippets.

@Sanjogsharma
Last active September 10, 2015 15:39
Show Gist options
  • Select an option

  • Save Sanjogsharma/f64aa26b9e77c6ba71e6 to your computer and use it in GitHub Desktop.

Select an option

Save Sanjogsharma/f64aa26b9e77c6ba71e6 to your computer and use it in GitHub Desktop.
count occurance of words seperated by whitespace (python)
# count occurance of words seperated by whitespace
from collections import defaultdict
# remove punctuation parks
def removes_punc(string):
'''removes punctuations from string'''
punc = ['.', ',', '!']
new_string = ''
for letter in string:
if letter not in punc:
new_string += letter
return new_string
def word_counter(text):
'''counts words in a string'''
word_count = defaultdict(int)
text = removes_punc(text)
total_words = text.split()
for word in total_words:
word_count[word] += 1
return word_count
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment