pyspark 解析固定宽度的文本文件 [英] pyspark parse fixed width text file

查看:21
本文介绍了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 的 substr 函数可以处理固定宽度的列,例如:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆