python统计一个字符串中单词出现次数

#!/usr/bin/env python
# -*- coding:utf-8 -*-

str = "cease to struggle and you cease to live"
# 切分字符串
str2 = str.split(" ")
word_dict = dict()
for word in str2:
    if word in word_dict:
        word_dict[word] += 1
    else:
        word_dict[word] = 1
print(word_dict)

//输出
{'cease': 2, 'to': 2, 'struggle': 1, 'and': 1, 'you': 1, 'live': 1}
发布了19 篇原创文章 · 获赞 0 · 访问量 765

猜你喜欢

转载自blog.csdn.net/FloraLan666/article/details/104038671