Spark计算其中包含特定单词的行数

时间:2017-07-13 10:33:09

标签: apache-spark pyspark

我有一个日志文件,其中的行包含单词" error"在里面。如何在apache spark中计算包含该术语的总行数?

到目前为止,我正在使用这种方法。

from pyspark import SparkConf, SparkContext

conf = SparkConf().setMaster("local").setAppName("WordCount")
sc = SparkContext(conf = conf)

input = sc.textFile("errors.txt")
words = input.flatMap(lambda x: x for x if "errors" in input)
wordCounts = input.countByValue()

for word, count in wordCounts.items():
    print str(count)

但这种方法不起作用。谁能告诉我怎么算数?

编辑:scala中的等效项是

lines = spark.textFile("hdfs://...")
errors = lines.filter(_.startsWith("ERROR"))
errors.persist()

这行的python等价物是什么。

3 个答案:

答案 0 :(得分:2)

请使用以下代码段:

from pyspark import SparkConf, SparkContext

conf = SparkConf().setMaster("local").setAppName("errors")
sc = SparkContext(conf = conf)

lines = sc.textFile("errors.txt")
rdd = lines.filter(lambda x: "error" in x)
print rdd.count

答案 1 :(得分:0)

input.filter(lambda line : "error" in line).count()应该有用。

答案 2 :(得分:0)

感谢您的解决方案。我能够以另一种方式解决它

http://test_lara.com/foo
相关问题