PySpark 中的 Bigram 计数

cls*_*udt 4 python apache-spark pyspark pyspark-sql apache-spark-ml

我试图在 PySpark 中拼凑一个二元计数程序,它采用一个文本文件并输出每个适当二元的频率(句子中的两个连续单词)。

from pyspark.ml.feature import NGram

with use_spark_session("Bigrams") as spark:
    text_file = spark.sparkContext.textFile(text_path)
    sentences = text_file.flatMap(lambda line: line.split(".")) \
                        .filter(lambda line: len(line) > 0) \
                        .map(lambda line: (0, line.strip().split(" ")))  
    sentences_df = sentences.toDF(schema=["id", "words"])    
    ngram_df = NGram(n=2, inputCol="words", outputCol="bigrams").transform(sentences_df)
Run Code Online (Sandbox Code Playgroud)

ngram_df.select("bigrams") 现在包含:

+--------------------+
|             bigrams|
+--------------------+
|[April is, is the...|
|[It is, is one, o...|
|[April always, al...|
|[April always, al...|
|[April's flowers,...|
|[Its birthstone, ...|
|[The meaning, mea...|
|[April comes, com...|
|[It also, also co...|
|[April begins, be...|
|[April ends, ends...|
|[In common, commo...|
|[In common, commo...|
|[In common, commo...|
|[In years, years ...|
|[In years, years ...|
+--------------------+
Run Code Online (Sandbox Code Playgroud)

所以每个句子都有二元组列表。现在需要计算不同的二元组。如何?此外,整个代码似乎仍然不必要地冗长,所以我很乐意看到更简洁的解决方案。

小智 6

如果您已经使用了RDDAPI,则可以按照以下步骤操作

bigrams = text_file.flatMap(lambda line: line.split(".")) \
                   .map(lambda line: line.strip().split(" ")) \
                   .flatMap(lambda xs: (tuple(x) for x in zip(xs, xs[1:])))

bigrams.map(lambda x: (x, 1)).reduceByKey(lambda x, y: x + y)
Run Code Online (Sandbox Code Playgroud)

除此以外:

from pyspark.sql.functions import explode

ngram_df.select(explode("bigrams").alias("bigram")).groupBy("bigram").count()
Run Code Online (Sandbox Code Playgroud)