【问题标题】:utf-8 and latin-1 won't work while reading a csv file with pandas使用 pandas 读取 csv 文件时,utf-8 和 latin-1 将不起作用
【发布时间】:2018-02-06 18:26:15
【问题描述】:

我正在尝试读取包含法语字符(如 é、à 等)和带有 pandas 的电子邮件地址的 CSV 文件。

使用 utf-8 编码会出错。使用 latin-1 编码消除了我的 é。

知道我应该使用什么编码吗?

谢谢, 克里斯

【问题讨论】:

  • 你能告诉我们错误信息吗?
  • CSV 实际写入的编码是什么?引用Zen of Python,“面对歧义,拒绝猜测的诱惑。”。我们没有您的 CSV 文件,因此我们不知道您应该使用什么编码。
  • 这是我应该得到的:['word with é','word with à','word with è','mail@mail.com']。这就是我使用 latin1 时得到的结果:['word with \x8e'、'word with \x88'、'word with \x8f'、'mail@mail.com']。这是我使用 utf-8 时遇到的错误:UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8e in position 10: invalid start byte
  • 我的 CSV 文件是在 MAC 中使用 Excel 表创建的 > 另存为“逗号分隔值 (.csv)”

标签: pandas csv utf-8 iso-8859-1


【解决方案1】:
pd.read_csv(csv_file, encoding = 'iso-8859-1')

其中“iso-8859-1”是正确表示包括法国在内的西欧语言所需的编码

【讨论】:

    【解决方案2】:

    试试下面的

    #! /usr/bin/python
    # coding: utf-8
    import pandas
    file_content = open('some_file.csv')
    data = pandas.read_csv(file_content, encoding='utf-8', quotechar='"', 
    delimiter=';')
    

    【讨论】:

    • OP特别说UTF-8会抛出异常。
    • 谢谢塞巴斯蒂安。不幸的是,这不起作用。
    猜你喜欢
    • 1970-01-01
    • 2016-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-13
    • 2012-02-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多