pyspark单词统计(python编写)文件在hdfs上

在写代码之前先了解一下代码中一些方法的作用:
**sparkContext:**在Spark应用程序的执行过程中起着主导作用,它负责与程序和spark集群进行交互,包括申请集群资源、创建RDD、accumulators及广播变量等。
**sc.textFiles(path):**能将path 里的所有文件内容读出,以文件中的每一行作为一条记录的方式,文件的每一行 相当于 List中以 “,”号 隔开的一个元素,因此可以在每个partition中用for i in data的形式遍历处理Array里的数据。
**map(func):**将每个元素传递到函数func中,并将结果返回为一个新的数据集
**flatMap(func):**与map()相似,但每个输入元素都可以映射到0或多个输出结果
**reduceByKey(func):**应用于(K,V)键值对的数据集时,返回一个新的(K, V)形式的数据集,其中的每个值是将每个key传递到函数func中进行聚合
**saveAsTextFile:**会按照执行task的多少生成多少个文件

代码如下:

import os
import shutil
from pyspark import SparkConf, SparkContext
input = 'hdfs://master:9000/hello.txt'
output = 'hdfs://master:9000/out1'
sc = SparkContext('local', 'WordCount')
# 读取文件
test_file = sc.textFile(input)
# 切分单词
word = test_file.flatMap(lambda line: line.split(' '))
# 转换成键值对并计数
count = word.map(lambda word: (word, 1)).reduceByKey(lambda x, y: x + y)
# 输出结果
count.foreach(print)
# 删除输出目录
if os.path.exists(outputpath):  //判断目录是否存在
    shutil.rmtree(outputpath, True)  //目录存在删掉
# 将统计结果写入结果文件
counts.saveAsTextFile(output)


或者可以放在一起

import os
import shutil
from pyspark import SparkConf, SparkContext
input = 'hdfs://master:9000/hello.txt'
output = 'hdfs://master:9000/out1'
sc = SparkContext('local', 'WordCount')
test_file = sc.textFile(input).test_file.flatMap(lambda line: line.split(' ')).map(lambda word: (word, 1)).reduceByKey(lambda x, y: x + y)
test_file.foreach(print)
# 删除输出目录
if os.path.exists(outputpath):  //判断目录是否存在
    shutil.rmtree(outputpath, True)  //目录存在删掉
# 将统计结果写入结果文件
counts.saveAsTextFile(output)

  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小懒胖熊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值