首页 > 解决方案 > 如何根据字符数解析字符串?

问题描述

我正在尝试解析字符串并将结果附加到数据框中的新字段?在 SQL 中,它会像这样工作。

UPDATE myDF
SET theyear = SUBSTRING(filename, 52, 4),
SET themonth = SUBSTRING(filename, 57, 2),
SET theday = SUBSTRING(filename, 60, 2),
SET thefile = SUBSTRING(filename, 71, 99)

我想使用 Scala 来完成这项工作,因为我正在使用的数据帧非常庞大,使用它比使用 SQL 来做同样的事情要快很多。所以,根据我的研究,我认为它看起来像这样,但我不知道如何计算字段中的字符数。

以下是一些示例数据:

abc://path_to_all_files_in_data_lake/2018/10/27/Parent/CPPP1027.Mid.414.gz

我想得到年、月、日和文件名,所以在这个例子中,我希望数据框有这个。

在此处输入图像描述

val modifiedDF = df
  .withColumn("theyear", )
  .withColumn("themonth", )
  .withColumn("theday", )
  .withColumn("thefile", )

modifiedDF.show(false)

因此,我想将四个字段附加到数据框中:年、月、日和文件。然后,根据字符串中的字符数进行解析。谢谢。

标签: scaladatabricks

解决方案


我可能宁愿使用 RegEx 进行模式匹配而不是字符串长度。在这个简单的示例中,我使用以下方法提取主要日期模式,regexp_extract然后从那里构建其他列substring

%scala
import org.apache.spark.sql.functions._

val df = Seq( ( "abc://path_to_all_files_in_data_lake/2018/10/27/Parent/CPPP1027.Mid.414.gz" ), ( "abc://path_to_all_files_in_data_lake/2019/02/28/Parent/CPPP77.Mid.303.gz" ) )
  .toDF("somePath")
  .withColumn("theDate", regexp_extract($"somePath", "[0-9][0-9][0-9][0-9]/[0-9][0-9]/[0-9][0-9]", 0) )
  .withColumn("theYear", substring($"theDate", 1, 4 ) )
  .withColumn("theMonth", substring($"theDate", 6, 2 ) )
  .withColumn("theDay", substring($"theDate", 9, 2 ) )
  .withColumn("theFile", regexp_extract($"somePath", "[^/]+\\.gz", 0) )


df.show

我的结果:

我的结果

那对你有用吗?


推荐阅读