计算每个句子中的单词数Spark Dataframes

2 python apache-spark apache-spark-sql

我有一个Spark Dataframe,其中每一行都有一个评论。

+--------------------+
|          reviewText| 
+--------------------+
|Spiritually and m...|
|This is one my mu...|
|This book provide...|
|I first read THE ...|
+--------------------+
Run Code Online (Sandbox Code Playgroud)

我试过了:

SplitSentences = df.withColumn("split_sent",sentencesplit_udf(col('reviewText')))
SplitSentences = SplitSentences.select(SplitSentences.split_sent)
Run Code Online (Sandbox Code Playgroud)

然后我创建了函数:

def word_count(text):
    return len(text.split())

wordcount_udf = udf(lambda x: word_count(x))

df2 = SplitSentences.withColumn("word_count", 
  wordcount_udf(col('split_sent')).cast(IntegerType())
Run Code Online (Sandbox Code Playgroud)

我想计算每个评论(行)中每个句子的单词,但它不起作用。

Ram*_*jan 5

您可以使用split 内置函数拆分句子,并使用size 内置函数将数组的长度计算为

df.withColumn("word_count", F.size(F.split(df['reviewText'], ' '))).show(truncate=False)
Run Code Online (Sandbox Code Playgroud)

这样,您就不需要昂贵的udf函数

例如,假设您有一个句子数据框

+-----------------------------+
|reviewText                   |
+-----------------------------+
|this is text testing spliting|
+-----------------------------+
Run Code Online (Sandbox Code Playgroud)

上述申请后sizesplit功能你应该得到

+-----------------------------+----------+
|reviewText                   |word_count|
+-----------------------------+----------+
|this is text testing spliting|5         |
+-----------------------------+----------+
Run Code Online (Sandbox Code Playgroud)

如果您在一行中有多个句子,如下所示

+----------------------------------------------------------------------------------+
|reviewText                                                                        |
+----------------------------------------------------------------------------------+
|this is text testing spliting. this is second sentence. And this is the third one.|
+----------------------------------------------------------------------------------+
Run Code Online (Sandbox Code Playgroud)

然后,您将必须编写udf如下的函数

from pyspark.sql import functions as F
def countWordsInEachSentences(array):
    return [len(x.split()) for x in array]

countWordsSentences = F.udf(lambda x: countWordsInEachSentences(x.split('. ')))

df.withColumn("word_count", countWordsSentences(df['reviewText'])).show(truncate=False)
Run Code Online (Sandbox Code Playgroud)

这应该给你

+----------------------------------------------------------------------------------+----------+
|reviewText                                                                        |word_count|
+----------------------------------------------------------------------------------+----------+
|this is text testing spliting. this is second sentence. And this is the third one.|[5, 4, 6] |
+----------------------------------------------------------------------------------+----------+
Run Code Online (Sandbox Code Playgroud)

我希望答案是有帮助的