如何使用pyspark从文件中查找分隔符



是否有任何方法可以找到分隔符并使用spark-read读取该文件。基本上,我想使用spark-read 从文件中读取数据

我们需要三种类型的分隔符(,;|(,即(逗号、分号、管道(

csv_data = spark.read.load("path of file", format = "csv",header ='true').cache()

我们可以使用.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|
#+----+---+-------+

我在笔记本上用了这样的东西来获取delimeter:

import re
headerList=sc.textFile("yourPath").take(1)
headerString = ''.join(headerList)
result = re.search("(,|;|\|)", headerString)
delimiter = result.group()

最新更新