在Spark中处理文本文件而不会出现delimter

问题描述

我的文本文件很大(3 GB),并且想要在Spark中处理该文本文件。此文本文件中没有定界符。在第50个字符之后,新记录开始,但记录之间没有定界符。我对如何加载此数据和处理此文件一无所知?

sample.txt

此数据此数据此数据此数据此数据 此数据新数据集此此新数据集此数据此新数据集aa 此数据此数据新数据集此此数据此数据 此数据新数据集此此新数据集此数据此数据新 此数据此数据

sc.textFile('path/to/file.txt') # this not helping here as there is no delimiter between records

仅是为了识别我使用强调和强调的模式,但是我们知道文本文件没有强调和强调的是纯文本。

解决方法

我认为在这种情况下,我们需要使用 udf ,因为 regexp_extract_all 直到 Spark-3.1 版本

Example:

from pyspark.sql.functions import *
from pyspark.sql.types import *

#read the file as csv
df=spark.read.csv("<file_path>").toDF("val")

#udf to capture 50 character groups
def regex_all_matches(s):
    all_matches = re.findall(r'.{1,50}',s)
    return all_matches

#register udf and 
regex_all_matches_udf = udf(regex_all_matches,ArrayType(StringType()))

df2 = df.withColumn('val',explode(regex_all_matches_udf(col('val'))))

#+--------------------------------------------------+
#|val                                               |
#+--------------------------------------------------+
#|thisisdatathisisdatathisisdatathisisdatathisisdata|
#|thisisnewdatasetthisisnewdatasetthisisnewdatasetaa|
#|thisisdatathisisdatathisisdatathisisdatathisisdata|
#|thisisnewdatasetthisisnewdatasetthisisnewdatasetaa|
#|thisisdatathisisdatathisisdatathisisdatathisisdata|
#+--------------------------------------------------+

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...