scala - Spark CSV 读取忽略字符
问题描述
我通过 Zeppelin 使用 Spark 2.2.1。
现在我的火花读取代码如下:
val data = spark.read.option("header", "true").option("delimiter", ",").option("treatEmptyValuesAsNulls","true").csv("listings.csv")
我注意到当我使用该.show()
功能时,单元格向右移动。在 CSV 上,所有单元格都位于正确的位置,但通过 Spark 后,单元格将向右移动。我能够确定罪魁祸首:引文是错位的单元格。CSV 文件中有一些单元格是这样写的:
{电视、互联网、Wifi、空调、厨房、室内壁炉、暖气、家庭/儿童友好型、洗衣机、烘干机}
实际输出(请注意,我使用.select()
并选择了一些列来显示我遇到的问题。):
| description| amenities| square_feet| price|
+--------------------+--------------------+-----------------+--------------------+
|This large, famil...|"{TV,Internet,Wif...| Kitchen|""Indoor fireplace""|
|Guest room in a l...| "{TV,""Cable TV""| Internet| Wifi|
预期输出:
| description| amenities| square_feet| price|
+--------------------+--------------------+-----------------+--------------------+
|This large, famil...|"{TV,Internet,Wif...| 1400 | $400.00 ||
|Guest room in a l...| "{TV,""Cable TV""| 1100 | $250.00 ||
有没有办法摆脱引号或用撇号替换它们?撇号似乎不会影响数据。
解决方案
您正在寻找的是regexp_replace
具有语法的函数regexp_replace(str, pattern, replacement)
。
不幸的是,我无法重现您的问题,因为我不知道如何编写 Listings.csv 文件。
但是,下面的示例应该让您了解在 Spark 中处理数据帧时如何替换某些正则表达式模式。
这反映了您的原始数据
data.show()
+-----------+----------+-----------+--------+
|description| amenities|square_feet| price|
+-----------+----------+-----------+--------+
|'This large| famil...'| '{TV|Internet|
+-----------+----------+-----------+--------+
使用 regexp_replace 您可以像这样替换可疑的字符串模式
import org.apache.spark.sql.functions.regexp_replace
data.withColumn("amenitiesNew", regexp_replace(data("amenities"), "famil", "replaced")).show()
+-----------+----------+-----------+--------+-------------+
|description| amenities|square_feet| price| amenitiesNew|
+-----------+----------+-----------+--------+-------------+
|'This large| famil...'| '{TV|Internet| replaced...'|
+-----------+----------+-----------+--------+-------------+
使用此功能应该通过替换有问题的字符来解决您的问题。随意在该函数中使用正则表达式。
推荐阅读
- javascript - 仅显示 ReactJs 中 api 数据中的每 4 个项目
- html - React Material UI - 网格列高度属性
- c# - 使用 Android 应用程序操作日历事件
- go - 记录 http.ResponseWriter 内容
- javascript - Ionic/Capacitor iOS App 不会从第三方源加载脚本
- javascript - 如何在 JavaScript 中解析时间?
- python - 绘制从 xarray 数据集到 AxesGrid 的子图
- flutter - 使用令牌和云函数的最佳 FCM 方法
- prolog - 解释基本 Prolog 结果
- angular - 从 JAX-RS ContainerRequestFilter 重定向到 Angular 路由