开发语言 学习 大数据 2027.12.31 Python 词频统计 - 方法2:

📅 2026-11-30 👤 拼多多助力营销技巧 📂 手赚APP 👁️ 538 次阅读

练习:使用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',mode='w',encoding='utf8'

)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',mode='r',encoding='UTF-8') as file_obj:

result_dict = {}

while True:

# 2- 读取文件内容。可以通过readline()

line = file_obj.readline()

if line=='':

break

# 3- 将一行内容切分得到多个单个的单词。并且对单词进行过滤filter

word_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,单词出现的次数作为value

for word in word_list:

exist_flag = (word in result_dict.keys())

if not exist_flag:

# 4.1- 如果单词在字典中不存在,直接新增一对key-value(1)

word_num = 1

else:

# 4.2- 如果单词在字典中已经存在,那么将value+=1之后更新字典的value

# 5-从字典中取出key对应的次数,进行累加操作

word_num += 1

result_dict[word] = word_num

# 6-最终就得到结果

print(result_dict)

参考文章

标签: 拼多多助力网站平台 赚钱项目 拼多多助力网 首码项目 手赚APP
拼多多助力营销技巧