【问题标题】:remove a single quote in a string with pySpark using regex使用正则表达式使用 pySpark 删除字符串中的单引号
【发布时间】:2019-12-18 20:59:10
【问题描述】:

我需要删除字符串中的单引号。列名称是关键字。我有一个隐藏在字符串中的数组。所以我需要在 Spark Dataframe 中使用 Regex 从字符串的开头和结尾删除单引号。字符串如下所示:

Keywords=
'
  [
      "shade perennials"," shade loving perennials"," perennial plants"," perennials"," perennial flowers"," perennial plants for shade"," full shade perennials"
  ]
'

我尝试了以下方法:

remove_single_quote = udf(lambda x: x.replace(u"'",""))
cleaned_df = spark_df.withColumn('Keywords', remove_single_quote('Keywords'))

但是单引号还在,我也试过(u"\'","")

【问题讨论】:

    标签: regex apache-spark pyspark


    【解决方案1】:
    from pyspark.sql.functions import regexp_replace
    
    new_df = data.withColumn('Keywords', regexp_replace('Keywords', "\'", ""))
    

    【讨论】:

      【解决方案2】:

      试试 regexp_replace

      from pyspark.sql.functions import regexp_replace,col
          cleaned_df = spark_df.withColumn('Keywords', regexp_replace('Keywords',"\'",""))
      

      from pyspark.sql import functions as f
          cleaned_df = spark_df.withColumn('Keywords', f.regexp_replace('Keywords',"\'",""))
      

      我没有测试过它,但应该可以工作

      import ast
      
          cleaned_df = spark_df.withColumn('Keywords',ast.literal_eval('Keywords'))
      

      refer

      【讨论】:

      • 我运行了这两种方法,但单引号仍然出现在我的行​​中:/
      • 作为替代方案,您可以将此字符串转换为列表,然后访问第一个第 0 个元素
      • 事实上你甚至不需要转换成列表你可以直接从字符串中访问第 0 个元素
      • 请更新答案
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-21
      • 2013-01-13
      • 2011-05-13
      • 1970-01-01
      • 2020-05-07
      相关资源
      最近更新 更多