【问题标题】:How to find the frequency of a word in a line, in a text file - Pyspark如何在文本文件中查找一行中单词的频率 - Pyspark
【发布时间】:2022-01-21 03:15:04
【问题描述】:

我设法制作了一个如下所示的 RDD(在 Pyspark 中):

[('This', (0, 1)), ('is', (0, 1)), ('the', (0, 1)), ('100th', (0, 1))...]

我使用了以下代码: RDD=sc.textFile(_filepath_)

test1 = RDD.zipWithIndex().flatMap(lambda x: ((i,(x[1],1)) for i in x[0].split(" ")))

实际上,[(word, (line, freq)] 所以上面的单词来自文件的第一行(因此是 0),freq 是文本中所有单词的 1,我希望它计算这个单词出现的次数这个特定的行,用于整个 RDD。 我想到了 .reduceByKey(lambda x, y: x + y),但是当我之后执行.take(5) 之类的操作时,它会冻结(Ubuntu 终端 - 具有大量 RAM/磁盘空间的 Oracle VirtualBox,如果有帮助的话)。

我需要的基本上是,如果'This'这个词在第一行并且出现了7次,那么结果将是[('This', (0, 7)), ...]

【问题讨论】:

  • 请勿在问题中发布图像或代码链接。请编辑您的问题以包含图片文本。

标签: python apache-spark pyspark rdd word-count


【解决方案1】:

解决了,但答案可能不是最优的。

RDD = sc.textFile(_filepath_) 
test1 = RDD.zipWithIndex().flatMap(lambda x: ((i,(x[1],1)) for i in x[0].split(" "))) 
test2 = test1.map(lambda x: ((x[0], x[1][0]), x[1][1])).reduceByKey(lambda x, y: x + y) 
Result_RDD = test2.map(lambda x: (x[0][0], (x[0][1], x[1])))

【讨论】:

    猜你喜欢
    • 2013-02-02
    • 1970-01-01
    • 2020-01-22
    • 1970-01-01
    • 2017-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-23
    相关资源
    最近更新 更多