我正在尝试使用PySpark的MapReduce实现单词计数。我想能够计数的次数一对字出现在一行文字。你知道吗
例如,如果我有一句话:一只黑狗追逐黑球。你知道吗
输出可以是('a','black'):2,因为'black'在带有'a'的行上出现两次。你知道吗
我有以下代码来计算单个单词出现的次数,但我正在努力学习如何成对计数:
text_file = sc.textFile("filepath")
import re, string
string.punctuation
punc = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
def uni_to_clean_str(x):
converted = x.encode('utf-8')
lowercased_str = converted.lower()
lowercased_str = lowercased_str.replace('--',' ')
clean_str = lowercased_str.translate(None, punc)
return clean_str
one_RDD = text_file.flatMap(lambda x:uni_to_clean_str(x).split())
one_RDD = one_RDD.map(lambda x: (x,1))
one_RDD = one_RDD.reduceByKey(lambda x,y: x + y)
one_RDD.saveAsTextFile("filepath")
如果我用这个例句,它会返回:('a',1),等等
任何帮助都将不胜感激。非常感谢!你知道吗
目前没有回答
相关问题 更多 >
编程相关推荐