数据准备

数据下载:《莎士比亚全集》

我们先来看看原始数据:首先将数据加载到RDD,然后显示数据框的前15行。

shakespeareDF = sqlContext.read.text(fileName)
shakespeareDF.show(15, truncate=False)

输出如下:

+-------------------------------------------------------+
|value                                                  |
+-------------------------------------------------------+
|1609                                                   |
|                                                       |
|THE SONNETS                                            |
|                                                       |
|by William Shakespeare                                 |
|                                                       |
|                                                       |
|                                                       |
|                     1                                 |
|  From fairest creatures we desire increase,           |
|  That thereby beauty's rose might never die,          |
|  But as the riper should by time decease,             |
|  His tender heir might bear his memory:               |
|  But thou contracted to thine own bright eyes,        |
|  Feed'st thy light's flame with self-substantial fuel,|
+-------------------------------------------------------+

数据清洗

因为原始数据包括标点符号,大小写字符,空行。所以我们需要对数据进行清洗。所以我提供了一个removePunctuation函数。这个函数将去掉了标点,删除了句子两端的多余的空格,并将字符全部转换为小写。

from pyspark.sql.functions import regexp_replace, trim, lower
def removePunctuation(column):
    return lower(trim(regexp_replace(column, '[^\w\s]', '')))

为了使用这个函数,我们先来看一个例子。

sentenceDF = (sqlContext
              .createDataFrame([('Hi, you!',),
                                (' No under_score!',),
                                (' *      Remove punctuation then spaces  * ',)], ['sentence']))
sentenceDF.show(truncate=False)

原始的数据框输出如下:

+------------------------------------------+
|sentence                                  |
+------------------------------------------+
|Hi, you!                                  |
| No under_score!                          |
| *      Remove punctuation then spaces  * |
+------------------------------------------+

接下来使用removePunctuation进行清洗。

from pyspark.sql.functions import col
(sentenceDF
 .select(removePunctuation(col('sentence')).alias('sentence'))
 .show(truncate=False))

清洗后的数据框输出如下:

+------------------------------+
|sentence                      |
+------------------------------+
|hi you                        |
|no under_score                |
|remove punctuation then spaces|
+------------------------------+

有了这个函数,我们就能对《莎士比亚全集》进行清洗了,首先将shakespeare.txt加载到RDD,并使用removePunctuation函数对数据进行清洗.

from pyspark.sql.functions import col
fileName = "shakespeare.txt"
shakespeareDF = (sqlContext
                 .read
                 .text(fileName)
                 .select(removePunctuation(col('value')).alias('value')))
shakespeareDF.show(15, truncate=False)

清洗后的数据框输出如下:

+-------------------------------------------------+
|value                                            |
+-------------------------------------------------+
|1609                                             |
|                                                 |
|the sonnets                                      |
|                                                 |
|by william shakespeare                           |
|                                                 |
|                                                 |
|                                                 |
|1                                                |
|from fairest creatures we desire increase        |
|that thereby beautys rose might never die        |
|but as the riper should by time decease          |
|his tender heir might bear his memory            |
|but thou contracted to thine own bright eyes     |
|feedst thy lights flame with selfsubstantial fuel|
+-------------------------------------------------+

接下来,我们使用split函数分隔每一行的句子,然后用explode函数将行转列,得到一个包括所有单词的数据框,最后使用where函数过滤掉数据框的空行。

from pyspark.sql.functions import split, explode
shakeWordsDF = (shakespeareDF
                .select(explode(split(shakespeareDF.value, ' ')).alias('word'))
                .where("word<>''"))
shakeWordsDF.show()
shakeWordsDFCount = shakeWordsDF.count()
print shakeWordsDFCount

转换后的数据框输出如下:

+-----------+
|       word|
+-----------+
|       1609|
|        the|
|    sonnets|
|         by|
|    william|
|shakespeare|
|          1|
|       from|
|    fairest|
|  creatures|
|         we|
|     desire|
|   increase|
|       that|
|    thereby|
|    beautys|
|       rose|
|      might|
|      never|
|        die|
+-----------+

数据统计

为了统计单词数,我提供一个wordCount函数,它作用是按单词进行分组,然后统计各个分组中单词的个数,最后返回包含word和count列的数据框。

def wordCount(wordListDF):
    return wordListDF.groupBy('word').count()

先来看一个使用wordCount函数的例子:

wordsDF = (sqlContext
           .createDataFrame([('cat',), ('elephant',), ('rat',), ('rat',), ('cat', )], ['word']))
wordCount(wordsDF).show()
wordCount(words)

wordCount函数返回的数据框输出如下:

+--------+-----+
|    word|count|
+--------+-----+
|     cat|    2|
|     rat|    2|
|elephant|    1|
+--------+-----+

接下来使用wordCount函数统计《莎士比亚全集》的单词数,然后按照count列降序排列。

from pyspark.sql.functions import desc
topWordsAndCountsDF = wordCount(shakeWordsDF).orderBy(desc('count'))
topWordsAndCountsDF.show()

排序后的数据框输出如下所示

+----+-----+
|word|count|
+----+-----+
| the|27361|
| and|26028|
|   i|20681|
|  to|19150|
|  of|17463|
|   a|14593|
| you|13615|
|  my|12481|
|  in|10956|
|that|10890|
|  is| 9134|
| not| 8497|
|with| 7771|
|  me| 7769|
|  it| 7678|
| for| 7558|
|  be| 6857|
| his| 6857|
|your| 6655|
|this| 6602|
+----+-----+

总结

可以看到,出现次数较多的单词大都是停用词。

[spark案例学习] 单词计数的更多相关文章

  1. hadoop笔记之MapReduce的应用案例(WordCount单词计数)

    MapReduce的应用案例(WordCount单词计数) MapReduce的应用案例(WordCount单词计数) 1. WordCount单词计数 作用: 计算文件中出现每个单词的频数 输入结果 ...

  2. 大数据学习——Storm学习单词计数案例

    需求:计算单词在文档中出现的次数,每出现一次就累加一次 遇到的问题 这个问题是<scope>provided</scope>作用域问题 https://www.cnblogs. ...

  3. [spark案例学习] WEB日志分析

    数据准备 数据下载:美国宇航局肯尼迪航天中心WEB日志 我们先来看看数据:首先将日志加载到RDD,并显示出前20行(默认). import sys import os log_file_path =' ...

  4. Storm入门2-单词计数案例学习

     [本篇文章主要是通过一个单词计数的案例学习,来加深对storm的基本概念的理解以及基本的开发流程和如何提交并运行一个拓扑] 单词计数拓扑WordCountTopology实现的基本功能就是不停地读入 ...

  5. Spark学习笔记1——第一个Spark程序:单词数统计

    Spark学习笔记1--第一个Spark程序:单词数统计 笔记摘抄自 [美] Holden Karau 等著的<Spark快速大数据分析> 添加依赖 通过 Maven 添加 Spark-c ...

  6. Spark: 单词计数(Word Count)的MapReduce实现(Java/Python)

    1 导引 我们在博客<Hadoop: 单词计数(Word Count)的MapReduce实现 >中学习了如何用Hadoop-MapReduce实现单词计数,现在我们来看如何用Spark来 ...

  7. Spark基础学习精髓——第一篇

    Spark基础学习精髓 1 Spark与大数据 1.1 大数据基础 1.1.1 大数据特点 存储空间大 数据量大 计算量大 1.1.2 大数据开发通用步骤及其对应的技术 大数据采集->大数据预处 ...

  8. Kafka与Spark案例实践

    1.概述 Kafka系统的灵活多变,让它拥有丰富的拓展性,可以与第三方套件很方便的对接.例如,实时计算引擎Spark.接下来通过一个完整案例,运用Kafka和Spark来合理完成. 2.内容 2.1 ...

  9. 使用Scala实现Java项目的单词计数:串行及Actor版本

    其实我想找一门“具有Python的简洁写法和融合Java平台的优势, 同时又足够有挑战性和灵活性”的编程语言. Scala 就是一个不错的选择. Scala 有很多语言特性, 建议先掌握基础常用的: ...

随机推荐

  1. centos rar安装

    wget http://www.rarsoft.com/rar/rarlinux-x64-5.1.1.tar.gz tar -zxvf rarlinux-x64-5.1.1.tar.gz # cd r ...

  2. 初学c# -- 学习笔记(三)

    结合前面学的许多东西,写了一个小程序.会话.自定义滚动条.css等等.小程序没有用数据库,主要不知道该用哪种,以后再说吧.登录也简单,就输入用户名就可以了. 百度是个好东西,写程序时候,需要什么图就直 ...

  3. ceph与openstack对接

    对接分为三种,也就是存储为openstack提供的三类功能1.云盘,就好比我们新加的硬盘2.原本的镜像也放在ceph里,但是我没有选择这种方式,原因是因为后期有要求,但是我会把这个也写出来,大家自己对 ...

  4. poj 1276 Cash Machine(多重背包)

    Cash Machine Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 33444   Accepted: 12106 De ...

  5. div里面的id与for

    <input class="select" type="checkbox" value="1" id="checkboxjc ...

  6. otter双主同步安装与配置

    otter是阿里的开源数据同步项目,资源地址就不用说了哈,网上找,阿里云论坛关于单方向同步的配置已经很清楚了,理论上说,双主同步也不复杂,但是毕竟 是数据库,比较重要,配置双主的时候,总觉得心里没底, ...

  7. Powershell获取并导出指定日期EventLog

    $date = Get-Date 28/07/16 Get-EventLog -After $date "Application"|Export-Csv c:\ming.csv

  8. 网站appache的ab命令压力测试性能

    ①:相关不错的博文链接:http://johnnyhg.iteye.com/blog/523818 ②:首先配置好对应的环境上去,有对应的命令 ③:压力测试的指令如下: 1. 最基本的关心两个选项 - ...

  9. Oracle中的正则表达式

    检查约束 --密码的长度必须在3-6 --年龄必须在1-120 --性别只能是男或女 --电话号码必须满足电话的格式: 手机格式,座机格式 drop table test; select * from ...

  10. django单元测试

        django 单元测试小结 django 测试 从前很少写单元测试了,特别是web应用.最近不知不觉喜欢起来这个事情了,发现单元测试对于软件的模块,正交性有很大促进作用,因为函数,模块写的不合 ...