You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python处理CSV时无法删除<0xa0>字符如何解决

问题根因

你原来的代码无法生效是两个核心原因:

  • Python中字符串是不可变对象,你调用strip()、replace()方法都会返回新的字符串,不会修改原eachitem[0]的内容,等于做了无用操作
  • <0xa0>是终端/编辑器显示非间断空格(也就是原始页面的&nbsp;)的可视化表示,它本身不是字符串内容,对应的Unicode码位是\xa0,所以你匹配u'<0xa0>'永远匹配不到

方案1:生成CSV阶段直接过滤特殊字符

修改你的写入逻辑为以下代码:

for eachitem in prods_dict[eachkey]:
    # 处理MPN字段:先替换非间断空格,再移除首尾空白
    cleaned_mpn = str(eachitem[0]).replace('\xa0', '').strip()
    # 把处理后的值替换回原列表
    eachitem[0] = cleaned_mpn
    writer.writerow(eachitem)

如果要更稳妥覆盖其他不可见空白字符,可以改用正则统一处理:

import re
for eachitem in prods_dict[eachkey]:
    # 匹配所有Unicode空白字符(包括非间断空格、全角空格等)替换为空
    cleaned_mpn = re.sub(r'\s', '', str(eachitem[0]))
    eachitem[0] = cleaned_mpn
    writer.writerow(eachitem)

方案2:已生成的CSV文件批量修复

直接用Python读取旧CSV,处理后写入新CSV即可,代码示例:

import csv

input_path = "你的旧文件路径.csv"
output_path = "清理后的新文件路径.csv"

with open(input_path, 'r', encoding='utf-8') as in_f, open(output_path, 'w', encoding='utf-8', newline='') as out_f:
    reader = csv.reader(in_f)
    writer = csv.writer(out_f)
    for row in reader:
        # 处理每一行的所有字段,也可以指定只处理MPN对应的列下标
        cleaned_row = [cell.replace('\xa0', '').strip() for cell in row]
        writer.writerow(cleaned_row)

运行后新生成的CSV就不会再有<0xa0>字符了。


内容的提问来源于stack exchange,提问作者N Miaoulis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 21:18:00