如何解决在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|
#+--------------------------------------------------+
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。