def countWords(document): \"\"\" Takes a string as an argument and returns a dic
ID: 3744132 • Letter: D
Question
def countWords(document):
"""
Takes a string as an argument and returns a dictionary with the word count
>>> article1='''
... He will be the president of the company; right now
... he is a vice president.
... But he ..... himself, is no sure of it...
... (Later he will see the importance of these.)
... '''
>>> article2='''
... Two new vents from the erupting Kilauea volcano on Hawaii
... prompted officials on Tuesday afternoon to order the immediate evacuation of
... residents remaining in Lanipuna Gardens. All 1,700 residents of Leilani Estates,
... as well as the smaller Lanipuna, had previously been ordered to evacuate.
... But that does not mean they all have.
... '''
>>> countWords(article1)
{'he': 4, 'will': 2, 'be': 1, 'the': 3, 'president': 2, 'of': 3, 'company': 1, 'right': 1, 'now': 1, 'is': 2, 'a': 1, 'vice': 1, 'but': 1, 'himself': 1, 'no': 1, 'sure': 1, 'it': 1, 'later': 1, 'see': 1, 'importance': 1, 'these': 1}
>>> countWords(article2)
{'two': 1, 'new': 1, 'vents': 1, 'from': 1, 'the': 3, 'erupting': 1, 'kilauea': 1, 'volcano': 1, 'on': 2, 'hawaii': 1, 'prompted': 1, 'officials': 1, 'tuesday': 1, 'afternoon': 1, 'to': 2, 'order': 1, 'immediate': 1, 'evacuation': 1, 'of': 2, 'residents': 2, 'remaining': 1, 'in': 1, 'lanipuna': 2, 'gardens': 1, 'all': 2, 'leilani': 1, 'estates': 1, 'as': 2, 'well': 1, 'smaller': 1, 'had': 1, 'previously': 1, 'been': 1, 'ordered': 1, 'evacuate': 1, 'but': 1, 'that': 1, 'does': 1, 'not': 1, 'mean': 1, 'they': 1, 'have': 1}
>>> countWords(55)
'Invalid input'
>>> countWords([3.5,6])
'Invalid input'
"""
# --- YOU CODE STARTS HERE
Explanation / Answer
def countWords(document): words = document.split() d = {} for word in words: modified_word = '' for ch in word: if ch.isalpha(): modified_word += ch modified_word = modified_word.strip().lower() if len(modified_word) > 0: if modified_word not in d: d[modified_word] = 0 d[modified_word] += 1 return d article1=''' ... He will be the president of the company; right now ... he is a vice president. ... But he ..... himself, is no sure of it... ... (Later he will see the importance of these.) ... ''' article2=''' ... Two new vents from the erupting Kilauea volcano on Hawaii ... prompted officials on Tuesday afternoon to order the immediate evacuation of ... residents remaining in Lanipuna Gardens. All 1,700 residents of Leilani Estates, ... as well as the smaller Lanipuna, had previously been ordered to evacuate. ... But that does not mean they all have. ... ''' print(countWords(article1)) print(' ') print(countWords(article2))
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.