【问题标题】:How to calculate the count of words per line in pyspark如何计算pyspark中每行的字数
【发布时间】:2020-03-11 05:41:42
【问题描述】:

我试过了:

rdd1= sc.parallelize(["Let's have some fun.",
  "To have fun you don't need any plans."])
output = rdd1.map(lambda t: t.split(" ")).map(lambda lists: (lists, len(lists)))
output.foreach(print)

输出:

(["Let's", 'have', 'some', 'fun.'], 4)
(['To', 'have', 'fun', 'you', "don't", 'need', 'any', 'plans.'], 8)

我得到了每行单词的总数。但我想要每行每个单词的计数。

【问题讨论】:

  • 你想要单词的数量和出现次数吗?

标签: pyspark rdd


【解决方案1】:

你可以试试这个:

from collections import Counter 

output = rdd1.map(lambda t: t.split(" ")).map(lambda lists: dict(Counter(lists)))

我举一个小python例子:

from collections import Counter

example_1 = "Let's have some fun."
Counter(example_1.split(" "))
# [{"Let's": 1, 'have': 1, 'some': 1, 'fun.': 1}

example_2 = "To have fun you don't need any plans."
Counter(example_2.split(" "))
# {'To': 1, 'have': 1, 'fun': 1, 'you': 1, "don't": 1, 'need': 1, 'any': 1, 'plans.': 1}]

【讨论】:

    【解决方案2】:

    根据您的输入和我的理解,请找到以下代码。只需对您的代码进行细微更改:

    output = rdd1.flatMap(lambda t: t.split(" ")).map(lambda lists: (lists, 1)).reduceByKey(lambda x,y : x+y)  
    

    您使用map 来拆分数据。而是使用flatMap。它会将你的字符串分解成单词。 PFB输出:

    output.collect()
    
    [('have', 2), ("Let's", 1), ('To', 1), ('you', 1), ('need', 1), ('fun', 1), ("don't", 1), ('any', 1), ('some', 1), ('fun.', 1), ('plans.', 1)]
    

    【讨论】:

      猜你喜欢
      • 2022-10-23
      • 2017-07-16
      • 2021-10-10
      • 1970-01-01
      • 2018-10-03
      • 1970-01-01
      • 2019-04-22
      • 1970-01-01
      相关资源
      最近更新 更多