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字符
相关推荐
2501_9336707913 小时前
2026年中专大数据技术专业可考证书清单
大数据
CJenny13 小时前
Claude Code常用操作和使用方法
人工智能·python
九河云13 小时前
纺织印染“数字色差仪”:光谱+AI模型一次调色成功省染料12%
大数据·人工智能·安全·机器学习·数字化转型
事橙199914 小时前
KITTI数据集国内下载链接
人工智能·python·yolo
2502_9116791414 小时前
KEYSIGHT是德 N1912A功率计:宽带多通道功率测量的标杆之选
大数据·网络·信息与通信·信号处理
HarmonLTS14 小时前
Python人工智能深度开发:技术体系、核心实践与工程化落地
开发语言·人工智能·python·算法
weixin_4624462314 小时前
Python 解析 Excel 图表(Chart)信息实战:从 xlsx 中提取标题、字体和数据
python·数据分析·excel·报表自动化
weixin_4624462314 小时前
使用 Python 脚本自动化管理 Docker 容器:启动、修改密码、删除及系统资源监控
python·docker·自动化·系统监控
weixin_4624462314 小时前
Python 异步下载文件实战:使用 asyncio + aiohttp 实现高并发下载
python·并发下载
bloglin9999914 小时前
anaconda环境中如何生成requirements
python