PySpark获取Dataframe中所有非ASCII字符

python 复制代码
from pyspark.sql import SparkSession
from pyspark.sql.functions import col, concat_ws, explode, split, coalesce, lit
from pyspark.sql.types import StringType

spark = SparkSession.builder.appName("InvalidCharacterFinder").getOrCreate()

# 假设已存在DataFrame df
# df = ...

# 获取所有字符串类型列名
string_columns = [f.name for f in df.schema.fields if isinstance(f.dataType, StringType)]
result = []

if string_columns:
    # 处理空值并合并字符串列
    non_null_cols = [coalesce(col(c), lit("")).alias(c) for c in string_columns]
    combined_df = df.select(non_null_cols).select(concat_ws("", *string_columns).alias("merged_str"))
    
    # 拆分字符并过滤空字符串
    chars_df = combined_df.withColumn("char", explode(split(col("merged_str"), "")))\
                          .filter(col("char") != "")
    
    # 定义合法字符集合
    allowed_chars = set('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!'
                        '"#$%&\'()*+,-./:;<=>?@[]^_`{|}~')
    
    # 收集非法字符并去重
    unique_invalid = chars_df.rdd.map(lambda x: x.char)\
                             .filter(lambda c: c not in allowed_chars)\
                             .distinct()\
                             .collect()
    
    # 按首次出现顺序保留字符(分布式环境无法保证绝对顺序)
    seen = set()
    ordered_result = []
    for char in unique_invalid:
        if char not in seen:
            ordered_result.append(char)
            seen.add(char)
    result = ordered_result

print("非法字符集合:", ''.join(result))

代码说明:

  1. 数据准备:通过DataFrame Schema识别所有字符串类型的列
  2. 空值处理 :使用coalesce函数将NULL转换为空字符串,确保后续字符串合并有效
  3. 列合并 :使用concat_ws将多个字符串列的值合并为单个字符串
  4. 字符拆分:通过split+explode将字符串拆分为单个字符,并过滤空字符
  5. 非法字符过滤:使用RDD操作过滤不在白名单中的字符,并通过distinct去重
  6. 结果处理:使用有序集合保持字符首次出现的顺序(注意:分布式环境下无法保证绝对顺序)

注意事项:

  • 最终结果字符顺序可能与实际数据中的出现顺序不完全一致
  • 白名单包含94个可打印ASCII字符(排除空格和控制字符)
  • 使用RDD操作提升分布式处理性能
  • 最终结果字符串可能包含各类特殊符号、中文、表情符号等非标准ASCII字符
相关推荐
蓝速科技1 小时前
会议室门牌公告通知发布选型与落地指南丨蓝速科技
大数据·运维·数据库·人工智能·科技
GPU实战笔记1 小时前
云端 Python 开发:JupyterLab 还是 VS Code Remote-SSH?
python·vs code·jupyterlab·remote-ssh·远程开发
狗狗狗狗狗乐啊2 小时前
搭一个 AI 对话工作台 AChat:从 0 到可用的完整记录(一)
python·react.js·ai编程
白猫不黑2 小时前
Python实现简易Web弱口令爆破与防护方案
python·web安全·计算机·网络安全·黑客·信息安全·渗透测试
kuuailetianzi3 小时前
Python初识:定位、优势与发展历程
python
guoran_shini3 小时前
LLM微调-训练垂类问答模型
python·lora·sft
basketball6163 小时前
Python FastAPI 介绍以及常用方法
python·fastapi·vllm·ai infra
论文复现现场3 小时前
企业知识库 RAG 用什么模型便宜?GLM-5.3-Flash 长文本 API 实测
python·rag·企业知识库·大模型api·glm-5.3-flash
梦在远山后4 小时前
从手写 Loop 到可恢复 Runtime:用 LangGraph、PostgreSQL Checkpoint 与 AG-UI 跑通中断恢复
python·langchain·agent
SelectDB4 小时前
同等资源下 Apache Doris 4.2 vs StarRocks 4.1.1:1TB SSB 与 TPC-H 性能实测
大数据·数据库·数据分析