scala - 如何根据字符数解析字符串?
问题描述
我正在尝试解析字符串并将结果附加到数据框中的新字段?在 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)
因此,我想将四个字段附加到数据框中:年、月、日和文件。然后,根据字符串中的字符数进行解析。谢谢。
解决方案
我可能宁愿使用 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
我的结果:
那对你有用吗?
推荐阅读
- c# - 使用 Serilog 登录到电子邮件接收器
- android-studio - 在 Android 视图中创建文件夹
- php - PHP:无法在虚拟主机中将数据插入数据库,但在本地它正在使用 CI 工作
- node.js - 在 node.js 中,我如何知道 fs.stat() 是否会为给定的文件/路径/卷/fs 返回可用的 crtime 和/或出生时间字段?
- ios - 无法为发布而构建 - Flutter、Xcode
- c++ - 查找圆内最近的坐标
- django - Django 和 React.js 生产
- python - discord.py 无法识别命令
- python - 如何根据行索引和列名在两个数据框之间设置多个值?
- wordpress - 图像未在 WordPress 仪表板中上传