使用 pyspark 对文本文件中所有单词的长度求和的问题

Issues summing the length of all the words in a text file using pyspark

我正在尝试使用 databricks 上的 pyspark 总结文本文件中的所有字母。我已经成功地得到了每个单词的长度,但很难将它们加起来

示例文本文件

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut a leo massa. Phasellus maximus

代码

lee_file = sc.textFile("/FileStore/tables/lee.txt")
lee_counts = lee_file.flatMap(lambda line: line.split(" ")).map(lambda word: (word, 
len(word)))

counts_df2 = sqlContext.createDataFrame(lee_counts).toDF("word", "len")
display(counts_df2.take(10))

您可以使用 pyspark sql 的求和函数。

from pyspark.sql.functions import sum

total_count_df = counts_df2.select(sum("len"))

要将计数放入变量中,请使用 collect。

total_count = total_count_df.collect()[0][0]