python - 如何避免将新行计为 Spark 中的单词?

标签 python regex apache-spark

我正在尝试在 lorem ipsum 上运行字数统计示例;即计算给定文本文件中的单词频率。作为单词分割的规则,我想使用任何非字符实例。我有以下 python 代码:

import re
from pyspark import SparkContext
print "-----------------===========================-----------------"
print "-----------------==========Staring==========-----------------"
print "-----------------===========================-----------------"
sc = SparkContext(appName = "simple app")

print "-----------------===========================-----------------"
print "-----------------==========Loaded file======-----------------"
print "-----------------===========================-----------------"
text_file = sc.textFile("lorem.txt")

print "-----------------===========================-----------------"
print "-----------------==========  Process  ======-----------------"
print "-----------------===========================-----------------"
counts = text_file.flatMap(lambda line: re.split(r'\W*', line.rstrip())) \
         .map(lambda word: (word, 1)) \
         .reduceByKey(lambda a, b: a + b) \
         .map(lambda (a,b): (b, a)) \
         .sortByKey(False)

output = counts.collect()
counts.saveAsTextFile("test.txt")
sc.stop()
for x in output:
    print (x[0], x[1])

它几乎按预期工作。主要问题是它计算新行。如果我理解正确,这是由于正则表达式的工作方式造成的,但我找不到解决方法。我做错了什么?

最佳答案

请注意,line.rstrip() 仅去除空格。但它可以采用 line.rstrip(badchars) 中的参数,该参数将删除 badchars 中的所有内容。

即使换行符与空词和其他垃圾一起进入 RDD,您也可以通过添加 RDD.filter() 来过滤掉它们。步骤到您的工作流程。 filter 为 RDD 的每个元素调用一个函数,并返回返回 true 的元素的 RDD。

将换行符作为单词删除的几种方法:

明确地寻找它

counts = text_file.flatMap(lambda line: re.split(r'\W*', line.rstrip())) \
         .filter(lambda word: word!="\n") \
         .map(lambda word: (word, 1)) \
         .reduceByKey(lambda a, b: a + b) \
         .map(lambda (a,b): (b, a)) \
         .sortByKey(False)

过滤字长 > 1 个字符

counts = text_file.flatMap(lambda line: re.split(r'\W*', line.rstrip())) \
         .filter(lambda word: len(word)>1) \
         .map(lambda word: (word, 1)) \
         .reduceByKey(lambda a, b: a + b) \
         .map(lambda (a,b): (b, a)) \
         .sortByKey(False)

关于python - 如何避免将新行计为 Spark 中的单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32065551/

相关文章:

python - 如何使用 numpy 数组在 Keras 中设置权重?

java - 如何使用 Java 正则表达式解析骰子符号?

apache-spark - 如何在 Spark 2.0 程序(实际上是 pyspark 2.0)中编写正确的入口点?

cassandra - 有时无法使用 Spark 打开 native 连接

apache-spark - 我可以将具有 log4j.appender.file.File 的 dataproc 的 log4j.properties 文件作为 gcs 路径吗?

java - 如何使用绝对路径从 Java 运行 Python 文件?

python - 根据 Keras 预测,如何在 OpenCV 中绘制边界框?

python - ec2 每次启动都运行脚本

r - 如何只保留 R 中复杂字符串中的信息?

javascript - 从 Javascript/Regex 中的 YouTube 链接中提取视频 ID