python statistical occurrences of words in a string

#!/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}
Published 19 original articles · won praise 0 · Views 765

Guess you like

Origin blog.csdn.net/FloraLan666/article/details/104038671