Spark下使用python写worldCount

  • A+
所属分类:Python Spark

安装spark就省略了,网上很多方法。

Spark下使用python写worldCount

test-data.txt文件

  1. a b c
  2. aaa
  3. bbb
  4. ccc
  5. a b c
  6. c
  7. b
  8. a

vi wordcount.py

  1. #!/usr/bin/env python
  2. #-*-conding:utf-8-*-
  3. import logging
  4. from operator import add
  5. from pyspark import SparkContext
  6. logging.basicConfig(format='%(message)s', level=logging.INFO)
  7. #import local file
  8. test_file_name = "file:///var/lib/hadoop-hdfs/spark_test/test-data.txt"
  9. out_file_name = "file:///var/lib/hadoop-hdfs/spark_test/spark-out"
  10. sc = SparkContext("local","wordcount app")
  11. # text_file rdd object
  12. text_file = sc.textFile(test_file_name)
  13. # counts
  14. counts = text_file.flatMap(lambda line: line.split(" ")).map(lambda word: (word, 1)).reduceByKey(lambda a, b: a + b)
  15. counts.saveAsTextFile(out_file_name)

读取文件默认是从hdfs读取文件,也可以指定sc.textFile("路径").在路径前面加上hdfs://表示从hdfs文件系统上读

本地文件读取 sc.textFile("路径").在路径前面加上file:// 表示从本地文件系统读,如file:///home/user/Spark/README.md

运行程序使用spark-submit

$spark-submit /var/lib/hadoop-hdfs/spark_test/wordcount.py

查看结果

cat spark-out/part-00000

  1. (u'a'3)
  2. (u''1)
  3. (u'c'3)
  4. (u'b'3)
  5. (u'aaa'1)
  6. (u'bbb'1)
  7. (u'ccc'1)

参考:http://blog.csdn.NET/vs412237401/article/details/51823228

R语言神经网络模型银行客户信用评估数据
误差分位数的默示有效估计与\ 自回归时间序列的预测区间
基于大数据的用户特征分析
2016年度中国软件开发者白皮书下载(PDF)

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: