首页 > 解决方案 > 显示单词不同表示的问题

问题描述

我正在使用 PySpark 进行字数统计,其中我需要处理的任务之一是显示一个单词的所有表示形式(即 apple、Apple、aAPPLe 等)

目前,我的代码只显示单词的小写版本,但它计算所有表示。我知道这是因为我在开始时将文本文件中的所有单词都小写了,但我不确定如何更改它以便我的 wordReps 将显示所有表示。

hussle = sc.textFile("SOME_TEXT_FILE")

def removePunc(x):
    bars = x.encode('utf-8')
    lowerBars = bars.lower()
    cleanBars = lowerBars.translate(None, string.punctuation)
    return cleanBars

words = hussle.flatMap(lambda x: removePunc(x).split())

total_words = words.count()

wordCount = words.map(lambda x: (x,1)).reduceByKey(lambda x,y: x + y).map(lambda x:(x[0],x[1],x[1]/float(total_words))).sortByKey(False)
wordReps = words.map(lambda word: (word.lower(), word)).reduceByKey(lambda word1, word2: word1 + " " + word2 if word2 not in word1 else word1)
wordsFinal = wordCount.join(wordReps)

我的预期输出应该是这样的:

'all' (4, 'all All aLL')

而是,我得到:

'all' (4, 'all')

标签: pythonapache-sparkpyspark

解决方案


推荐阅读