统计字符串中各单词个数

方法一:

text = 'I love python very much and I want to learn it well'
# 拆分
words = text.split(' ')
# print(words)
# 去重
diff_words = list(set(words))
# print(diff_words)
# 统计单词个数列表
counts = []
for i in range(len(diff_words)):
    counts.append(0)
    # print(counts)
# 遍历单词列表,统计哥哥单词个数
for i in range(len(words)):
    for j in range(len(diff_words)):
        if diff_words[j] == words[i]:
            counts[j] = counts[j] + 1

# 输出统计结果
for word_count in zip(diff_words, counts):
    print(word_count)

在这里插入图片描述

方法二:用collections模块的Counter来进行词频统计

text = 'I love python very much and I want to learn it well'
words = text.split(' ')
from collections import Counter

# print(Counter(words))
x=Counter(words)
for key in x.keys():
    print('{}:{}'.format(key,x[key]))

在这里插入图片描述

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐