>>> from collections import Counter >>> SENTENCE = "a b A b c b d b d e f e g e h e i e j e 0" >>> occurence_dict = word_occurrence(SENTENCE) >>> all(occurence_dict[word] == count for word, count ... in Counter(SENTENCE.split()).items()) True >>> dict(word_occurrence
(sentence: str)
| 4 | |
| 5 | |
| 6 | def word_occurrence(sentence: str) -> dict: |
| 7 | """ |
| 8 | >>> from collections import Counter |
| 9 | >>> SENTENCE = "a b A b c b d b d e f e g e h e i e j e 0" |
| 10 | >>> occurence_dict = word_occurrence(SENTENCE) |
| 11 | >>> all(occurence_dict[word] == count for word, count |
| 12 | ... in Counter(SENTENCE.split()).items()) |
| 13 | True |
| 14 | >>> dict(word_occurrence("Two spaces")) |
| 15 | {'Two': 1, 'spaces': 1} |
| 16 | """ |
| 17 | occurrence: defaultdict[str, int] = defaultdict(int) |
| 18 | # Creating a dictionary containing count of each word |
| 19 | for word in sentence.split(): |
| 20 | occurrence[word] += 1 |
| 21 | return occurrence |
| 22 | |
| 23 | |
| 24 | if __name__ == "__main__": |