如何使用pyspark从文件中找到定界符

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

有什么方法可以找到分隔符并使用spark read读取该文件。基本上我想使用spark read从文件中读取数据

我们期望三种类型的定界符(,; |),即(逗号,分号,竖线)

csv_data = spark.read.load("path of file", format = "csv",header ='true').cache()
python apache-spark pyspark delimiter
1个回答
1
投票

我们可以使用.textFile来获取csv文件的first行,并捕获分配给变量的delimiter

  • 使用delimiter变量读取csv文件

Example:

#sample data
$ cat test.csv
#NAME|AGE|COUNTRY
#a|18|USA
#b|20|Germany
#c|23|USA

#read as textfile and get first row then createdataframe with stringtype
#using regexp_extract function matching only ,|; and extracting assign to delimiter
delimiter=spark.createDataFrame(sc.textFile("file_path/test.csv").take(1),StringType()).\
withColumn("chars",regexp_extract(col("value"),"(,|;|\\|)",1)).\
select("chars").\
collect()[0][0]

delimter
#u'|'

#read csv file with delimiter
spark.read.\
option("delimiter",delimiter).\
option("header",True).\
csv("file_path/test.csv").show()
#+----+---+-------+
#|NAME|AGE|COUNTRY|
#+----+---+-------+
#|   a| 18|    USA|
#|   b| 20|Germany|
#|   c| 23|    USA|
#+----+---+-------+
© www.soinside.com 2019 - 2024. All rights reserved.