第八次作业

WordCount程序任务:

程序

WordCount

输入

一个包含大量单词的文本文件

输出

文件中每个单词及其出现次数(频数),

并按照单词字母顺序排序,

每个单词和其频数占一行,单词和频数之间有间隔

1.用你最熟悉的编程环境,编写非分布式的词频统计程序。

  • 读文件
  • 分词(text.split列表)
  • 按单词统计(字典,key单词,value次数)
  • 排序(list.sort列表)
  • 输出

(1)

# 导入扩展库
import re # 正则表达式库
import collections # 词频统计库
import numpy as np # numpy数据处理库
import jieba # 结巴分词
import wordcloud # 词云展示库
from PIL import Image # 图像处理库
import matplotlib.pyplot as plt # 图像展示库

# 读取文件
fn = open('nj.txt',encoding='UTF-8') # 打开文件
string_data = fn.read() # 读出整个文件
fn.close() # 关闭文件

# 文本预处理
pattern = re.compile(u'\t|\n|\.|-|:|;|\)|\(|\?|"') # 定义正则表达式匹配模式
string_data = re.sub(pattern, '', string_data) # 将符合模式的字符去除

# 文本分词
seg_list_exact = jieba.cut(string_data, cut_all = False) # 精确模式分词
object_list = []
remove_words = [u'的', u',',u'和', u'是', u'随着', u'对于', u'对',u'等',u'能',u'都',u'。',u' ',u'、',u'中',u'在',u'了',
u'通常',u'如果',u'我们',u'需要',u'(',u')',u'】',u'【',u':',u';',u'为',u'就'] # 自定义去除词库

for word in seg_list_exact: # 循环读出每个分词
if word not in remove_words: # 如果不在去除词库中
object_list.append(word) # 分词追加到列表

# 词频统计
word_counts = collections.Counter(object_list) # 对分词做词频统计
word_counts_top10 = word_counts.most_common(10) # 获取前10最高频的词
print (word_counts_top10) # 输出检查

# 词频展示
mask = np.array(Image.open('jxc.jpg')) # 定义词频背景
wc = wordcloud.WordCloud(
font_path='C:/Users/cyw/Desktop/simhei.ttf', # 设置字体格式
mask=mask, # 设置背景图
max_words=200, # 最多显示词数
max_font_size=100 # 字体最大值
)

wc.generate_from_frequencies(word_counts) # 从字典生成词云
image_colors = wordcloud.ImageColorGenerator(mask) # 从背景图建立颜色方案
wc.recolor(color_func=image_colors) # 将词云颜色设置为背景图方案
plt.imshow(wc) # 显示词云
plt.axis('off') # 关闭坐标轴
plt.show() # 显示图像

 

(2)

复制代码
import re

#打开read.txt并以字符串形式输出文件内容
file=open("read.txt","r")
str=file.read()
print(str)

# 利用正则将所有非字母的字符过滤掉
str = re.sub(r"[^a-zA-Z]+", " ",str)
print("过滤后的字符串:",str)

#拆分成列表
str = str.split(" ")
# 去除多余的空项
str.remove("")
print("拆分成列表:",str)

# 生成字典的key列表
dict_keys = []
for i in str:
    if i not in dict_keys:
        dict_keys.append(i)
print("key列表:",dict_keys)

# 定义空字典
words_dict = {}

# 往字典写入key值
words_dict.fromkeys(dict_keys)

# 遍历key列表,利用count函数统计单词出现次数
for j in dict_keys:
    words_dict[j] = str.count(j)
print("字典:",words_dict)

#默认排序方式给已拆分的单词排序
dict_keys.sort()
print("按字母排序:",dict_keys)
复制代码

编译运行结果如下:

There are several ways to create and maintain a harmonious dormitory life. Firstly, you have to evaluate your life style and try to get rid of your
dirty habits, if there are any. In conclusion, we should try our best to build a harmonious dormitory life for the sake of good study and
good life.
过滤后的字符串: There are several ways to create and maintain a harmonious dormitory life Firstly you have to evaluate your life style and try to get rid of your dirty habits if there are any In conclusion we should try our best to build a harmonious dormitory life for the sake of good study and good life
拆分成列表: ['There', 'are', 'several', 'ways', 'to', 'create', 'and', 'maintain', 'a', 'harmonious', 'dormitory', 'life', 'Firstly', 'you', 'have', 'to', 'evaluate', 'your', 'life', 'style', 'and', 'try', 'to', 'get', 'rid', 'of', 'your', 'dirty', 'habits', 'if', 'there', 'are', 'any', 'In', 'conclusion', 'we', 'should', 'try', 'our', 'best', 'to', 'build', 'a', 'harmonious', 'dormitory', 'life', 'for', 'the', 'sake', 'of', 'good', 'study', 'and', 'good', 'life']
key列表: ['There', 'are', 'several', 'ways', 'to', 'create', 'and', 'maintain', 'a', 'harmonious', 'dormitory', 'life', 'Firstly', 'you', 'have', 'evaluate', 'your', 'style', 'try', 'get', 'rid', 'of', 'dirty', 'habits', 'if', 'there', 'any', 'In', 'conclusion', 'we', 'should', 'our', 'best', 'build', 'for', 'the', 'sake', 'good', 'study']
字典: {'There': 1, 'are': 2, 'several': 1, 'ways': 1, 'to': 4, 'create': 1, 'and': 3, 'maintain': 1, 'a': 2, 'harmonious': 2, 'dormitory': 2, 'life': 4, 'Firstly': 1, 'you': 1, 'have': 1, 'evaluate': 1, 'your': 2, 'style': 1, 'try': 2, 'get': 1, 'rid': 1, 'of': 2, 'dirty': 1, 'habits': 1, 'if': 1, 'there': 1, 'any': 1, 'In': 1, 'conclusion': 1, 'we': 1, 'should': 1, 'our': 1, 'best': 1, 'build': 1, 'for': 1, 'the': 1, 'sake': 1, 'good': 2, 'study': 1}
按字母排序: ['Firstly', 'In', 'There', 'a', 'and', 'any', 'are', 'best', 'build', 'conclusion', 'create', 'dirty', 'dormitory', 'evaluate', 'for', 'get', 'good', 'habits', 'harmonious', 'have', 'if', 'life', 'maintain', 'of', 'our', 'rid', 'sake', 'several', 'should', 'study', 'style', 'the', 'there', 'to', 'try', 'ways', 'we', 'you', 'your']

在Ubuntu中实现运行。

  • 准备txt文件
  • gedit f1.txt
  • 编写py文件
  • 1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    path = '/home/hadoop/pythonproject/f1.txt'
    with open(path) as f:
        text=f.read()
    words=text.split()
     
    wc={}
    for word in words:
        wc[word]=wc.get(word,0)+1
    wclist=list(wc.items())
    wclist.sort(key=lambda x:x[1],reverse=True)
     
    print(wclist)
  • python3运行py文件分析txt文件
  •  

     

 

2.用MapReduce实现词频统计

2.1编写Map函数

  • 编写mapper.py
  • 复制代码
    #!/usr/bin/env python
    import sys
    for line in sys.stdin:
        line=line.strip()
        words=line.split()
        for word in words:
            print "%s\t%s" % (word,1)
    复制代码
  • 授予可运行权限
  • 本地测试mapper.py‘
  • echo "a b a c"| ./mapper.py
  • ./mapper.py

    python mapper.py

     

     

     

     

     使用第一行的解释器运行,ctrl+d结束输入

2.2编写Reduce函数

  •  

     

  • 编写reducer.py
  • 复制代码
    #!/usr/bin/env python
    from operator import itemgetter
    import sys
    
    current_word = None
    current_count = 0
    word = None
    
    for line in sys.stdin:
        line = line.strip()
        word,count = line.split('\t',1)
        try:
            count = int(count)
        except ValueError:
            continue
        if current_word == word:
            current_count += count
        else:
            if current_word:
                print "%s\t%s" % (current_word,current_count)
            current_count = count
            current_word = word
    
    if word == current_word:
        print "%s\t%s" % (current_word,current_count)
    复制代码

     

  • 授予可运行权限
  •  

     

  • 本地测试reducer.py
  • echo "a b a c" | ./mapper.py | ./reducer.py

  •  

      echo "a b a c" | ./mapper.py |sort | ./reducer.py

2.3分布式运行自带词频统计示例

  • 启动HDFS与YARN
  •  

     

  • 准备待处理文件,上传到HDFS上
  •  

     

  • 运行实例hadoop-mapreduce-examples-2.7.1.jar
  •  

  • 查看结果

 

 

2.4 分布式运行自写的词频统计

  • 用Streaming提交MapReduce任务:
    • 查看hadoop-streaming的jar文件位置:/usr/local/hadoop/share/hadoop/tools/lib/
    • 配置stream环境变量
    • 编写运行文件run.sh
    •  

       

    • 运行run.sh运行
  • 查看运行结果
  • 停止HDFS与YARN
  •  

     

     

posted @ 2021-11-23 14:36  下滑稽  阅读(65)  评论(0)    收藏  举报