WordCount程序任务:
|
程序 |
WordCount |
|
输入 |
一个包含大量单词的文本文件 |
|
输出 |
文件中每个单词及其出现次数(频数), 并按照单词字母顺序排序, 每个单词和其频数占一行,单词和频数之间有间隔 |
1.用你最熟悉的编程环境,编写非分布式的词频统计程序。
- 读文件
- 分词(text.split列表)
- 按单词统计(字典,key单词,value次数)
- 排序(list.sort列表)
- 输出
print("该程序可以进行词频统计。\n请注意选择中文词语或者英文单词。")
print("1.英文单词词频统计。\n2.中文词语频率统计。")
# noinspection PyUnresolvedReferences
import jieba
cidian = {}
k = 1
while k > 0:
option = input("请选择要进行的词频统计类型,填数字:")
wenben = input("注意文件路径格式。\n例如:E:\\python学习\\03实战演练\\文本.txt\n请输入文件路径:")
if option == 1:
txt = open(wenben, "r").read()
txt = txt.lower(txt)
for n in '.,?!':
txt = txt.replace(n," ")
words = txt.split()
for word in words:
if word not in cidian:
cidian[word] = 1
else:
cidian[word] = cidian[word] + 1
else:
txt = open(wenben, "r", encoding='utf-8').read()
words = jieba.lcut(txt)
for word in words:
if len(word) == 1:
continue
else:
if word not in cidian:
cidian[word] = 1
else:
cidian[word] = cidian[word] + 1
items = list(cidian.items())
items.sort(key=lambda x: x[1], reverse=True)
num = eval(input("你想显示前多少个最高单词/词语:"))
for i in range(num):
word, count = items[i]
print("{0:<10}{1:>5}".format(word, count))
2.用MapReduce实现词频统计
2.1编写Map函数
- 编写mapper.py
- 授予可运行权限
- 本地测试mapper.py

2.2编写Reduce函数
- 编写reducer.py
- 授予可运行权限
- 本地测试reducer.py


2.3分布式运行自带词频统计示例
- 启动HDFS与YARN
- 准备待处理文件
- 上传HDFS
- 运行hadoop-mapreduce-examples-2.7.1.jar
- 查看结果


2.4 分布式运行自写的词频统计
- 停止HDFS与YARN


浙公网安备 33010602011771号