Pyspark 对文本的操作,计算单词,独特的单词,最常见的单词

Pyspark operations on text, counting words, unique words, most common words

所以我基本上有一个文本,就是白鲸记。我把它转换成 RDD,它看起来像这样:

['The Project Gutenberg EBook of Moby Dick; or The Whale, by Herman',
 'Melville',
 'This eBook is for the use of anyone anywhere at no cost and with almost',

我必须计算所有单词的数量,计算唯一单词的数量,找到 10 个最常见的单词,并计算单词“whale”在一个整体中出现的频率。对于这个任务,我必须将每个短语拆分成单独的单词并删除空行:

MD = rawMD.filter(lambda x: x != "")

统计所有单词:

MDcount = MD.map(lambda x: x.split(" ")).flatMap(lambda x: x).filter(lambda x: x != "")
MDcount.count()

结果是:214376,我觉得不太好,但无论如何。

然后,对于独特的词:

MDcount.distinct().count()

结果:33282。还有一个问题,我不知道如何从“Whale's”这样的单词中删除“'s”

我试过这个:

DFcount = DFcount.select("Word", regexp_replace(col("Word"), "[_\"\'():;,.!?\-]", "").alias("Clear"))
DFcount = DFcount.drop("Word")
DFcount.distinct().count()

结果:23187字

但是,还不够好。维基百科说 Moby Dick 有大约 16000 个独特的单词。

最常用的单词:

Word_count = DFcount.groupby('Clear').count()
Word_count.orderBy(desc('count')).show(10)

结果:

+-----+-----+
|Clear|count|
+-----+-----+
|  the|13838|
|   of| 6654|
|  and| 6040|
|   to| 4582|
|    a| 4543|
|   in| 3950|
| that| 2857|
|  his| 2459|
|   it| 2060|
|    I| 1834|
+-----+-----+

以及“鲸鱼”的计数

RDDcount = DFcount.rdd.map(lambda x: x[0])
MDwh = RDDcount.filter(lambda x: "whale" in x)
print(MDwh.count())

结果:1329。维基百科说是 1,685

我认为有问题,因为我一直在文本中看到撇号、逗号等。我认为拆分句子并从中删除不必要的字符时存在问题。有没有人看到这些任务的正确答案?

我已经从古腾堡项目下载了这本书:Moby Dick; Or, The Whale by Herman Melville 纯文本 UTF-8。

Delete the obvious additional text from top and bottom and save it to a file: mobydick.

有一个函数 spark.read.text 可以读取文本文件并为每一行创建一个新行。这个想法是拆分行,展开它们并按单词对它们进行分组,然后执行所需的计算。

from pyspark.sql import SparkSession
import pyspark.sql.functions as F

spark = SparkSession.builder.getOrCreate()
df = spark.read.text("mobydick")
df = df.filter(F.col("value") != "")  # Remove empty rows

word_counts = (
    df.withColumn("word", F.explode(F.split(F.col("value"), "\s+")))
    .withColumn("word", F.regexp_replace("word", "[^\w]", ""))
    .groupBy("word")
    .count()
    .sort("count", ascending=False)
)

# Top 10
word_counts.show(10)

# All words count
word_counts.agg(F.sum("count").alias("count_all_words")).show()

# Whale count
word_counts.filter(F.col("word").rlike("(?i)whale")).agg(
    F.sum("count").alias("whale_count")
).show()

# Unique count
print("Unique words: ", word_counts.count())

结果:

+----+-----+                                                                    
|word|count|
+----+-----+
|the |13701|
|of  |6551 |
|and |5992 |
|to  |4513 |
|a   |4491 |
|in  |3905 |
|that|2865 |
|his |2462 |
|it  |2089 |
|I   |1942 |
+----+-----+

+---------------+
|count_all_words|
+---------------+
|212469         |
+---------------+

+-----------+
|whale_count|
+-----------+
|1687       |
+-----------+

Unique words:  21837

通过更多的清洁,您可以获得准确的结果。我猜这些独特的词有点不对劲,因为它们需要更多的清理和词干。