Spark CSV读取 忽略字符

问题描述 投票:0回答:1

我正在通过Zeppelin使用Spark 2.2.1。

现在我的Spark读取代码如下。

val data = spark.read.option("header", "true").option("delimiter", ",").option("treatEmptyValuesAsNulls","true").csv("listings.csv")

我注意到当我使用 .show() 函数,单元格会向右移动。在CSV上,所有的单元格都在正确的位置上,但是通过Spark后,单元格会向右移动。我找到了罪魁祸首:引号把单元格放错了位置。在CSV文件中,有一些单元格是这样写的。

{TV,Internet,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          ||

有没有办法去掉引号或用引号代替?撇号似乎不会影响数据。

scala apache-spark apache-zeppelin
1个回答
0
投票

你要找的是 regexp_replace 语法的函数 regexp_replace(str, pattern, replacement).

不幸的是,我无法重现你的问题,因为我不知道如何编写listing.csv文件。

不过,下面的例子应该能让你了解在Spark中处理数据框架时如何替换某些regex模式。

这反映了你的原始数据

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...'|
+-----------+----------+-----------+--------+-------------+

使用这个函数应该可以解决你的问题,将问题字符替换掉。在该函数中可以随意使用正则表达式。

© www.soinside.com 2019 - 2024. All rights reserved.