Spark下的词频计数是怎样进行的,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。
安装 Spark
下载 Spark 1.52 Pre-Built for hadoop 2.6 http://spark.apache.org/downloads.html。还需要预装 Java,Scala 环境。
将 Spark 目录文件放到 /opt/spark-hadoop 下,运行 ./spark-shell 会出现连接 Scale 窗口;运行 ./python/pyspark 会出现连接 Python 的窗口。这表示安装成功。
将 python 目录下 pyspark 复制到 Python 安装目录 /usr/local/lib/python2.7/dist-packages。这样才可以在程序中导入pyspark 库。
测试
#!/usr/bin/python
# -*- coding:utf-8 -*-
from pyspark import SparkConf, SparkContext
import os
os.environ["SPARK_HOME"] = "/opt/spark-hadoop"
APP_NAME = "TopKeyword"
if __name__ == "__main__":
logFile = "./README.md"
sc = SparkContext("local", "Simple App")
logData = sc.textFile(logFile).cache()
numAs = logData.filter(lambda s: 'a' in s).count()
numBs = logData.filter(lambda s: 'b' in s).count()
print("Lines with a: %i, lines with b: %i" % (numAs, numBs))
打印结果
Lines with a: 3, lines with b: 2
词频计数
#!/usr/bin/python
# -*- coding:utf-8 -*-
from pyspark import SparkConf, SparkContext
import os
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
os.environ["SPARK_HOME"] = "/opt/spark-hadoop"
def divide_word():
word_txt = open('question_word.txt', 'a')
with open('question_title.txt', 'r') as question_txt:
question = question_txt.readline()
while(question):
seg_list = jieba.cut(question, cut_all=False)
line = " ".join(seg_list)
word_txt.write(line)
question = question_txt.readline()
question_txt.close()
word_txt.close()
def word_count():
sc = SparkContext("local", "WordCount")
text_file = sc.textFile("./question_word.txt").cache()
counts = text_file.flatMap(lambda line: line.split(" ")) \
.map(lambda word: (word, 1)) \
.reduceByKey(lambda a, b: a + b)
counts.saveAsTextFile("./wordcount_result.txt")
if __name__ == "__main__"
word_count()
关于Spark下的词频计数是怎样进行的问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注天达云行业资讯频道了解更多相关知识。