统计字符串中各单词个数

方法一:

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

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐