【问题标题】:Remove non-ascii characters from CSV using pandas使用 pandas 从 CSV 中删除非 ascii 字符
【发布时间】:2022-01-27 23:11:59
【问题描述】:

我正在查询 SQL Server 数据库中的表并使用 pandas 导出到 CSV:

import pandas as pd

df = pd.read_sql_query(sql, conn)
df.to_csv(csvFile, index=False)

有没有办法在导出 CSV 时删除非 ascii 字符?

【问题讨论】:

  • df.to_csv(csvFile, index=False, encoding='ascii') ?

标签: python pandas non-ascii-characters


【解决方案1】:

您可以读入文件,然后使用正则表达式去除非 ASCII 字符:

df.to_csv(csvFile, index=False)

with open(csvFile) as f:
    new_text = re.sub(r'[^\x00-\x7F]+', '', f.read())

with open(csvFile, 'w') as f:
    f.write(new_text)

【讨论】:

  • 感谢您的快速响应。如果您有时间,是否可以将 CSV 的编码从 ANSI 更改为 UTF-8?我尝试将“encoding='utf-8'”附加到第二个打开函数,但 CSV 仍保留在 ANSI
  • 嗯......好吧,我不太确定如何帮助解决这个问题。也许写入文件(在to_csv 调用之后)是罪魁祸首?
【解决方案2】:

这就是我遇到的情况。这对我有用:

import re
regex = re.compile(r'[^\x00-\x7F]+') #regex that matches non-ascii characters
with open(csvFile, 'r') as infile, open('myfile.csv', 'w') as outfile:
    for line in infile:  #keep looping until we hit EOF (meaning there's no more lines to read)
        outfile.write(regex.sub('', line)) #write the current line in the input file to the output file, but if it matches our regex then we replace it with nothing (so it will get removed)

【讨论】:

    猜你喜欢
    • 2016-07-20
    • 2016-07-28
    • 1970-01-01
    • 1970-01-01
    • 2018-07-30
    • 1970-01-01
    • 2013-09-02
    • 1970-01-01
    相关资源
    最近更新 更多