I would like to ask for code review for my Python histogram word counter.
# Given a body of text, return a hash table of the frequency of each word.
"""
# I use a hash map as my data structure to create the histogram
# and add words into the dictionary
# if words are not in the dictionary, then I add those word into the dictionary
# final output is that we return the dictionary
"""
# Word Counter
# Given an body of text, return a hash table of the frequency of each word.
# Parameters
# Input: text {String}
# Output: {Hash Table}
# Constraints
# Capital and lower case versions of the same word should be counted is the same word.
# Remove punctuations from all words.
# Time: O(N)
# Space: O(N)
# Where N is the number of characters in the string.
# Examples
# 'The cat and the hat.' --> '{ the: 2, cat: 1, and: 1, hat: 1 }'`
# 'As soon as possible.' --> '{ as: 2, soon: 1, possible: 1 }'`
# 'It's a man, it's a plane, it's superman!' --> '{ its: 3, a: 2, man: 1, plane: 1, superman: 1 }'`
def word_count(sentence):
word_counter = {}
wordlist = sentence.lower().split()
for word in wordlist:
word = re.sub('[.,:*! ]', '', word)
if word in word_counter:
word_counter[word] += 1
else:
word_counter[word] = 1
return word_counter
example = word_count("It's a man, it's a plane, it's superman!")