80 Star 601 Fork 262

编程语言算法集 / Python

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
word_occurrence.py 870 Bytes
AI 代码解读
一键复制 编辑 原始数据 按行查看 历史
# Created by sarathkaul on 17/11/19
# Modified by Arkadip Bhattacharya(@darkmatter18) on 20/04/2020
from collections import defaultdict
def word_occurrence(sentence: str) -> dict:
"""
>>> 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("Two spaces"))
{'Two': 1, 'spaces': 1}
"""
occurrence: defaultdict[str, int] = defaultdict(int)
# Creating a dictionary containing count of each word
for word in sentence.split():
occurrence[word] += 1
return occurrence
if __name__ == "__main__":
for word, count in word_occurrence("INPUT STRING").items():
print(f"{word}: {count}")
Python
1
https://gitee.com/TheAlgorithms/Python.git
git@gitee.com:TheAlgorithms/Python.git
TheAlgorithms
Python
Python
master

搜索帮助