网站 app 哪个先做,深圳谷歌优化seo,湘潭网站建设 很好磐石网络,网站制作简介练习#xff1a;使用Python中的filter、map、reduce实现词频统计
样例数据#xff1a; hello world java python java java hadoop spark spark python 需求分析#xff1a;
1- 文件中有如上的示例数据
2- 读取文件内容。可以通过readline()
3- 将一行内容切分得到多个单…练习使用Python中的filter、map、reduce实现词频统计
样例数据 hello world java python java java hadoop spark spark python 需求分析
1- 文件中有如上的示例数据
2- 读取文件内容。可以通过readline()
3- 将一行内容切分得到多个单个的单词。并且对单词进行过滤filter
4- 数据结构转换将单词放到字典中
{
java:1
}
5-从字典中取出key对应的次数进行累加操作
6-最终就得到结果 方法1:
with open(./word_count.txt,modew,encodingutf8)as f:f.write(hello world java python java java hadoop spark spark python)import re
from collections import Counter# 读取文件
with open(./word_count.txt, r) as file:text file.read()# 将文本转换为小写并去除标点符号和特殊字符
text re.sub(r[^\w\s], , text.lower())# 使用空格分割文本为单词列表
words text.split()
# [hello, world, java, python, java, java, hadoop, spark, spark, python]
# 统计词频
word_counts Counter(words)
print(word_counts)
# Counter({java: 3, python: 2, spark: 2, hello: 1, world: 1, hadoop: 1})方法2: # 1- 文件中有如上的示例数据
with open(wordcount.txt,moder,encodingUTF-8) as file_obj:result_dict {}while True:# 2- 读取文件内容。可以通过readline()line file_obj.readline()if line:break# 3- 将一行内容切分得到多个单个的单词。并且对单词进行过滤filterword_list line.split()# 3.1- 过滤数据word_list filter(lambda word:word!world,word_list)# print(list(word_list),type(list(word_list)))# 4- 数据结构转换map将单词作为key单词出现的次数作为valuefor word in word_list:exist_flag (word in result_dict.keys())if not exist_flag:# 4.1- 如果单词在字典中不存在直接新增一对key-value(1)word_num 1else:# 4.2- 如果单词在字典中已经存在那么将value1之后更新字典的value# 5-从字典中取出key对应的次数进行累加操作word_num 1result_dict[word] word_num# 6-最终就得到结果print(result_dict)