问题描述
我的文本文件很大(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|
#+--------------------------------------------------+