pyspark解析固定宽度的文本文件 [英] pyspark parse fixed width text file
本文介绍了pyspark解析固定宽度的文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
试图解析固定宽度的文本文件.
Trying to parse a fixed width text file.
我的文本文件如下所示,我需要一个行ID,日期,一个字符串和一个整数:
my text file looks like the following and I need a row id, date, a string, and an integer:
00101292017you1234
00201302017 me5678
我可以使用sc.textFile(path)将文本文件读取到RDD. 我可以使用已解析的RDD和架构创建createDataFrame. 这是这两个步骤之间的解析.
I can read the text file to an RDD using sc.textFile(path). I can createDataFrame with a parsed RDD and a schema. It's the parsing in between those two steps.
推荐答案
Spark's substr function can handle fixed-width columns, for example:
df = spark.read.text("/tmp/sample.txt")
df.select(
df.value.substr(1,3).alias('id'),
df.value.substr(4,8).alias('date'),
df.value.substr(12,3).alias('string'),
df.value.substr(15,4).cast('integer').alias('integer')
).show()
将导致:
+---+--------+------+-------+
| id| date|string|integer|
+---+--------+------+-------+
|001|01292017| you| 1234|
|002|01302017| me| 5678|
+---+--------+------+-------+
具有拆分的列,您可以重新格式化格式,并像在常规spark数据框中那样使用它们.
Having splitted columns you can reformat and use them as in normal spark dataframe.
这篇关于pyspark解析固定宽度的文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文