2019-11-17 11:57:26 +00:00
|
|
|
# Created by sarathkaul on 17/11/19
|
2020-04-21 15:28:54 +00:00
|
|
|
# Modified by Arkadip Bhattacharya(@darkmatter18) on 20/04/2020
|
2019-11-17 11:57:26 +00:00
|
|
|
from collections import defaultdict
|
|
|
|
|
|
|
|
|
2022-05-20 04:03:54 +00:00
|
|
|
def word_occurrence(sentence: str) -> dict:
|
2019-11-17 11:57:26 +00:00
|
|
|
"""
|
|
|
|
>>> 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"
|
2022-05-20 04:03:54 +00:00
|
|
|
>>> occurence_dict = word_occurrence(SENTENCE)
|
2019-11-17 11:57:26 +00:00
|
|
|
>>> all(occurence_dict[word] == count for word, count
|
|
|
|
... in Counter(SENTENCE.split()).items())
|
|
|
|
True
|
2022-05-20 04:03:54 +00:00
|
|
|
>>> dict(word_occurrence("Two spaces"))
|
2020-04-21 15:28:54 +00:00
|
|
|
{'Two': 1, 'spaces': 1}
|
2019-11-17 11:57:26 +00:00
|
|
|
"""
|
2023-03-15 12:58:25 +00:00
|
|
|
occurrence: defaultdict[str, int] = defaultdict(int)
|
2019-11-17 11:57:26 +00:00
|
|
|
# Creating a dictionary containing count of each word
|
2020-04-21 15:28:54 +00:00
|
|
|
for word in sentence.split():
|
2020-01-18 12:24:33 +00:00
|
|
|
occurrence[word] += 1
|
|
|
|
return occurrence
|
2019-11-17 11:57:26 +00:00
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
2022-05-20 04:03:54 +00:00
|
|
|
for word, count in word_occurrence("INPUT STRING").items():
|
2019-11-17 11:57:26 +00:00
|
|
|
print(f"{word}: {count}")
|