【问题标题】:How to replace a list of special characters in a csv in python如何在python中替换csv中的特殊字符列表
【发布时间】:2017-01-21 14:49:39
【问题描述】:

我有一些 csv 文件可能包含也可能不包含不受欢迎的“”à 之类的字符,所以我想编写一个简单的脚本,该脚本将输入 csv 并用这些字符输出 csv(或其内容)替换为更标准的字符,因此在示例中:

bad_chars = '“”à'
good_chars = '""a'

到目前为止的问题是我的代码似乎生成了一个编码错误的 csv?在简化此过程和/或确保我的输出 csv 不会强制使用不正确的正则表达式编码(也许使用熊猫)方面的任何帮助将不胜感激?

尝试:

import csv, string
upload_path = sys.argv[1]
input_file = open('{}'.format(upload_path), 'rb')
upload_csv = open('{}_fixed.csv'.format(upload_path.strip('.csv')), 'wb')
data = csv.reader(input_file)
writer = csv.writer(upload_csv, quoting=csv.QUOTE_ALL)
in_chars = '\xd2\xd3'
out_chars = "''"
replace_list = string.maketrans(in_chars, out_chars)

for line in input_file:
    line = str(line)
    new_line = line.translate(replace_list)
    writer.writerow(new_line.split(','))

input_file.close()
upload_csv.close()

【问题讨论】:

  • 不是您提出的问题的直接解决方案,但请查看 unidecode 库 pypi.python.org/pypi/Unidecode/0.04.9 - 它将非 ascii 字符转换为 ascii 近似值(智能引号到直引号等)。

标签: python regex csv pandas


【解决方案1】:

当您用pandas 标签标记您的问题时 - 这是一个熊猫解决方案:

import pandas as pd

(pd.read_csv('/path/to/file.csv')
   .replace(r'RegEx_search_for_str', r'RegEx_replace_with_str', regex=True)
   .to_csv('/path/to/fixed.csv', index=False)
)

【讨论】:

  • 为什么不对 df 调用 str.translate ?
  • @Boud,因为.str. 方法只能应用于一列,所以我必须做类似df.apply(lambda x: x.astype(str).str.translate(...))
  • 好的,我看到你正在翻译性能循环与正则表达式替换
猜你喜欢
  • 2017-06-24
  • 2020-07-15
  • 2022-10-13
  • 2014-07-22
  • 2022-01-22
  • 1970-01-01
  • 2017-05-26
  • 1970-01-01
  • 2021-10-14
相关资源
最近更新 更多