PySpark中如何用Spark NLP的LanguageDetectorDL实现英文过滤
PySpark结合Spark NLP逐词过滤非英文单词实现方案
核心逻辑说明
- 现有
words列为array<string>类型,若直接将整列传入DocumentAssembler,组件默认会把数组内所有单词拼接为单个长文本生成标注文档,这种输入方式下的语言检测是对整段文本的判定,根本无法实现逐词筛选非英文内容的目标 - 检测流程需要拆解为逐词粒度:每个单词单独作为输入文本跑语言检测,仅保留检测结果为英文(语言代码为
en)的单词,再按原行的结构聚合回数组格式 - 用到的
LanguageDetectorDL组件输出的是文本对应的ISO语言编码,逐词检测时建议搭配低阈值的预训练轻量模型,避免长文本模型对短单词的识别偏差
分步实现代码
- 首先导入需要的依赖组件:
from sparknlp.annotator import LanguageDetectorDL from sparknlp.base import DocumentAssembler from pyspark.ml import Pipeline import pyspark.sql.functions as F
- 第一步:为原数据加唯一行标识,将
words数组拆为逐词单行,避免拆分后无法对应原行归属
# 生成全局唯一行ID df_with_rowid = df.withColumn("row_id", F.monotonically_increasing_id()) # 数组拆分为逐词行,保留单词在原数组中的位置信息 word_detail_df = df_with_rowid.select( "row_id", F.posexplode("words").alias("word_index", "word") ).filter(F.col("word").isNotNull() & (F.length(F.col("word")) > 0))
- 第二步:配置适配逐词输入的
DocumentAssembler,替换原本直接传入words列的配置
# 输入列改为拆分后的单个单词字段 doc_assembler = DocumentAssembler() \ .setInputCol("word") \ .setOutputCol("doc_content")
- 第三步:加载适配短文本检测的
LanguageDetectorDL预训练模型
# 加载轻量wiki训练的检测模型,置信度阈值设为0.5 lang_detector = LanguageDetectorDL.pretrained("ld_wiki_200", "en") \ .setInputCols("doc_content") \ .setOutputCol("lang_result") \ .setThreshold(0.5)
- 第四步:组装检测流程,逐词执行语言判定
# 构建处理Pipeline nlp_pipeline = Pipeline(stages=[doc_assembler, lang_detector]) # 执行检测 word_lang_df = nlp_pipeline.fit(word_detail_df).transform(word_detail_df) # 从标注结构中提取纯语言代码字段 word_lang_df = word_lang_df.withColumn( "detected_lang", F.col("lang_result.result")[0] )
- 第五步:过滤非英文单词,按原顺序聚合回数组格式,关联回原数据
# 仅保留判定为英文的单词,按原位置排序后聚合为数组 en_word_df = word_lang_df \ .filter(F.col("detected_lang") == "en") \ .orderBy("word_index") \ .groupBy("row_id") \ .agg(F.collect_list("word").alias("en_words")) # 关联回原表得到最终结果 final_df = df_with_rowid.join(en_word_df, on="row_id", how="left") \ .drop("row_id")
常见踩坑提示
- 不要尝试把
array<string>类型的列直接传给DocumentAssembler后跑语言检测,这种输入方式下所有单词会被拼接成单个长文本,最终只能得到整段文本的语言判定,无法实现逐词过滤 - 逐词检测时不要选用针对长文档优化的大参数
LanguageDetectorDL模型,这类模型对2-5个字符的短单词识别准确率极低,容易把普通英文短词误判为其他语言 - 如果某行所有单词都被判定为非英文,聚合后的
en_words列会是空数组,需要根据业务需求决定是保留空值还是直接过滤这类行
内容的提问来源于stack exchange,提问作者Samiksha
相关产品推荐
相关产品推荐

