【问题标题】:how to remove certain regular expression in PySpark using RDD?如何使用 RDD 删除 PySpark 中的某些正则表达式?
【发布时间】:2017-10-28 22:01:54
【问题描述】:

假设我试图删除这个正则表达式 "RT\s*@USER\w\w{8}:\s*" 我想在我的 RDD 中删除这种形式的正则表达式。

我目前的 RDD 是:

text = sc.textFile(...)
delimited = text.map(lambda x: x.split("\t"))

这是我试图删除正则表达式的部分。 我尝试执行以下 RDD 转换以摆脱与此正则表达式匹配的每个字符串,但这一切都给了我一个错误。

abc = delimited.map(lambda x: re.sub(r"RT\s*@USER\w\w{8}:\s*", " ", x))
TypeError: expected string or buffer

和

abc = re.sub(r"RT\s*@USER\w\w{8}:\s*", " ", delimited)
TypeError: expected string or buffer

和

abc = delimited.map(lambda x: re.sub(r"RT\s*@USER\w\w{8}:\s*", " ", text))
Exception: It appears that you are attempting to broadcast an RDD or reference an RDD from an action or transformation. RDD transformations and actions can only be invoked by the driver, not inside of other transformations; for example, rdd1.map(lambda x: rdd2.values.count() * x) is invalid because the values transformation and count action cannot be performed inside of the rdd1.map transformation. For more information, see SPARK-5063.

我想删除这个正则表达式,以便进行下一个 RDD 转换。如何在 PySpark 中编写此代码?

【问题讨论】:

    标签: apache-spark pyspark


    【解决方案1】:

    re.sub 需要一个字符串。

    • 在第一个匿名函数中:

      lambda x: re.sub(r"RT\s*@USER\w\w{8}:\s*", " ", x)
      

      x 是一个列表,因为您在之前的转换中拆分了行。

    • 在第二次尝试中,您传递了一个 RDD:delimeted

    • 在代码的第三个 sn-p 中,您传递另一个 RDD:text。

    如果您想为列表中的每个元素删除此正则表达式,请尝试以下操作:

    abc = delimited.map(lambda l: [re.sub(r"RT\s*@USER\w\w{8}:\s*", " ", x) for x in l])
    

    【讨论】:

      猜你喜欢
      • 2018-04-08
      • 2017-02-20
      • 1970-01-01
      • 1970-01-01
      • 2021-10-13
      • 2012-07-22
      • 1970-01-01
      • 1970-01-01
      • 2015-10-03
      相关资源
      最近更新 更多