我正在尝试在 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/