Python统计字符串中各单词个数案例含(collections模块的Counter)
统计字符串中各单词个数方法一: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 ra
·
统计字符串中各单词个数
方法一:
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]))
更多推荐
已为社区贡献6条内容
所有评论(0)