PySpark-读取带引号的csv文件

PySpark-读取带引号的csv文件,csv,apache-spark,pyspark,Csv,Apache Spark,Pyspark,我有csv文件如下 name|age|county|state|country "alex"john"|"30"|"burlington"|"nj"|"usa" 我使用spark读取csv文件 input_df = spark.read.format('csv').options(header='true', inferSchema='false', sep='|').load('s3://path_to_file') display(input_df) 输出(不确定为什么在alex“jo

我有csv文件如下

name|age|county|state|country
"alex"john"|"30"|"burlington"|"nj"|"usa"
我使用spark读取csv文件

input_df = spark.read.format('csv').options(header='true', inferSchema='false', sep='|').load('s3://path_to_file')

display(input_df)
输出(不确定为什么在alex“john”周围有引号,但在其他字段周围没有引号)

预期产出:

name        age county     state    country
alex"john   30  burlington  nj      usa

星火选择读取所有名称作为字符串(包括所有引号),如中间的引号将其抛出。只需删除第一个和最后一个双引号(如下所示):

为了在
中动态处理所有列,
我建议使用如下正则表达式:

from pyspark.sql import functions as F
df.select(*[F.regexp_replace(x,'^\"|\"$','').alias(x) for x in df.columns]).show()

#+---------+---+----------+-----+-------+
#|name     |age|county    |state|country|
#+---------+---+----------+-----+-------+
#|alex"john|30 |burlington|nj   |usa    |
#+---------+---+----------+-----+-------+

这是一个棘手的问题,因为没有什么东西能逃过这个内部引号(比如“\”)

如果找不到转义内部引号的方法,我建议您按原样读取数据,并使用regex_replace函数修剪周围的引号,如下所示:

从pyspark.sql.functions导入regexp\u replace
df=spark.read.option(“分隔符”、“真”).option(“推断模式”、“真”).option(“标题”、“真”).csv(“tmp.csv”)
withColumn(“格式化的名称”,regexp\u替换(df.name,^\“\\\”$,”).show()
输出:

+-----------+---+----------+-----+-------+--------------+
|姓名|年龄|县|州|国家|格式|名称|
+-----------+---+----------+-----+-------+--------------+
|“alex”john“| 30 |伯灵顿|新泽西|美国| alex”john|
+-----------+---+----------+-----+-------+--------------+

在实时情况下,我不知道列名,需要对所有列进行动态处理。假设我有如下输入:``name | age | country | state | country | alex\'john | 30 | burlington | nj | usa `。。如何使用转义字符以避免使用这个正则表达式?应该这样做:在实时情况下,我不知道列名,这需要对所有列进行动态处理
from pyspark.sql import functions as F
df.withColumn("name", F.expr("""substring(name,2,length(name)-2)""")).show()

#+---------+---+----------+-----+-------+
#|name     |age|county    |state|country|
#+---------+---+----------+-----+-------+
#|alex"john|30 |burlington|nj   |usa    |
#+---------+---+----------+-----+-------+
from pyspark.sql import functions as F
df.select(*[F.regexp_replace(x,'^\"|\"$','').alias(x) for x in df.columns]).show()

#+---------+---+----------+-----+-------+
#|name     |age|county    |state|country|
#+---------+---+----------+-----+-------+
#|alex"john|30 |burlington|nj   |usa    |
#+---------+---+----------+-----+-------+