Spark应用——进行字数统计
来源:互联网 发布:微信摇一摇抽奖软件 编辑:程序博客网 时间:2024/05/17 22:56
非结构性的文本数据在数据分析中越来越重要,Spark是分析这类型数据一个优秀的工具。这里我们构建一个简单的计数应用来统计莎士比亚全集中的高频词。该应用可以被扩展到更大规模的应用,例如统计维基百科中的高频词。
我们首先用python的元组列表和sqlContext.createDataFrame方法来构建数据结构,然后打印它的类型和架构。
wordsDF = sqlContext.createDataFrame([('cat',), ('elephant',), ('rat',), ('rat',), ('cat', )], ['word'])wordsDF.show()print type(wordsDF)wordsDF.printSchema()
现在我们建立一个新的数据结构,为每个词加上‘s’,使之成为复数。
from pyspark.sql.functions import lit, concatpluralDF = wordsDF.select(concat(wordsDF.word, lit('s')).alias('word'))pluralDF.show()
我们使用测试代码看上述操作是否正确
from databricks_test_helper import TestTest.assertEquals(pluralDF.first()[0], 'cats', 'incorrect result: you need to add an s')Test.assertEquals(pluralDF.columns, ['word'], "there should be one column named 'word'")
现在我们看一下每个词的长度(有多少字符)
from pyspark.sql.functions import lengthpluralLengthsDF = pluralDF.select(length('word'))pluralLengthsDF.show()
由于这里我们只用了5个词我们可以快速测试一下它们的长度是否正确
from collections import IterableasSelf = lambda v: map(lambda r: r[0] if isinstance(r, Iterable) and len(r) == 1 else r, v)Test.assertEquals(set(asSelf(pluralLengthsDF.collect())), {4, 9, 4, 4, 4}, 'incorrect values for pluralLengths')
现在我们来进行词数统计。首先我们使用groupBy函数将数据分类聚合,然后我们可以调用avg或者count函数来计算每组中词出现的次数或者平均数。
wordCountsDF = (wordsDF .groupBy('word').count())wordCountsDF.show()
同样我们进行一个快速的测试
Test.assertEquals(set(wordCountsDF.collect()), {('rat', 2), ('elephant', 1), ('cat', 2)}, 'incorrect counts for wordCountsDF')
接下来我们看一下用了多少个不同的词
uniqueWordsCount = wordCountsDF.count()print uniqueWordsCount
每个词平均出现的次数
averageCount = (wordCountsDF .groupBy().mean().collect())[0][0]print averageCount
现在我们将词数统计应用于文件
首先我们使用上述介绍的方法来快速定义一个函数,这个函数将接收一个词列表的数据结构,并返回一个词及相应计数的数据结构。
def wordCount(wordListDF): return wordListDF.groupBy('word').count() wordCount(wordsDF).show()
现在将标点符号去除,并统一大小写
from pyspark.sql.functions import regexp_replace, trim, col, lowerdef removePunctuation(column): return trim(lower(regexp_replace(column, '([^A-Za-z0-9\s]+)', ''))).alias('sentence')sentenceDF = sqlContext.createDataFrame([('Hi, you!',), (' No under_score!',), (' * Remove punctuation then spaces * ',)], ['sentence'])sentenceDF.show(truncate=False)(sentenceDF .select(removePunctuation(col('sentence'))) .show(truncate=False))
载入文本文件
fileName = ".../shakespeare.txt"shakespeareDF = sqlContext.read.text(fileName).select(removePunctuation(col('value')))shakespeareDF.show(15, truncate=False)
在进行统计前我们要解决两个问题。一是我们要将每行文本分割成词,二是要将空行或词过滤掉。
from pyspark.sql.functions import split, explodeshakeWordsDF = (shakespeareDF .select(explode(split(shakespeareDF.sentence,'[" "]')).alias('word')) .where("word != ''") )shakeWordsDF.show()shakeWordsDFCount = shakeWordsDF.count()print shakeWordsDFCount
最后我们使用之前定义的wordCount()函数来计数,并使用show()函数来查看出现次数最多的几个词。
from pyspark.sql.functions import desctopWordsAndCountsDF = wordCount(shakeWordsDF).orderBy(desc('count'))topWordsAndCountsDF.show()
至此我们构建了一个完整的关于词数统计的应用,并可以借Spark平台将它应用于大规模的词数快速统计。
阅读全文
0 0
- Spark应用——进行字数统计
- python简单应用:字数统计
- Python 简单应用--文章字数统计
- 字数统计
- 字数统计
- 字数统计
- 关于JS对正文进行字数统计的一段代码
- 对textview进行监听,统计edittext的字数
- 使用Spark、Ansj分词进行词频统计
- 【spark 词频统计】spark单词进行计数升级版
- Excel在统计分析中的应用—第二章—描述性统计-Part6-利用分析工具进行描述性统计
- Spark在文本统计中的简单应用
- VBA 字数统计
- 字数统计-简单哈希表
- 统计文本字数
- 统计页面字数
- JS统计字数
- TextArea统计字数
- Jsoup库,HTML的解析
- Struts 2.5
- Linux 集群没有root权限下包的安装方式
- 小车相关的
- Python廖雪峰实战web开发(Day11-编写日志创建页MVVC)
- Spark应用——进行字数统计
- Android Http请求
- LeetCode 344:Reverse String (c++)
- c#基础概念
- 《深入了解计算机系统》第一章《计算机系统漫游》知识点
- MySQL数据库-----------基础总结1
- Visual Studio 2010趣味编程完结版
- 刷清橙OJ--A1092.数据加密
- stl:find _first_of与search用法