【问题标题】:Loading UTF-8 file in Python 3 using numpy.genfromtxt使用 numpy.genfromtxt 在 Python 3 中加载 UTF-8 文件
【发布时间】:2016-01-05 05:23:30
【问题描述】:

我有一个从 WHO 网站下载的 CSV 文件(http://apps.who.int/gho/data/view.main.52160,下载,“CSV 格式的多用途表格”)。我尝试将文件加载到一个 numpy 数组中。这是我的代码:

import numpy
#U75 - unicode string of max. length 75
world_alcohol = numpy.genfromtxt("xmart.csv", dtype="U75", skip_header=2, delimiter=",")
print(world_alcohol)

我明白了

UnicodeDecodeError: 'ascii' 编解码器无法解码位置上的字节 0xc3 2:序数不在范围内(128)。

我猜 numpy 在读取字符串“Côte d'Ivoire”时有问题。该文件已正确编码为 UTF-8(根据我的文本编辑器)。我正在使用 Python 3.4.3 和 numpy 1.9.2。

我做错了什么?如何将文件读入 numpy?

【问题讨论】:

    标签: python csv numpy utf-8


    【解决方案1】:

    请注意原来的 2015 年日期。从那以后genfromtxt 得到了一个encoding 参数。


    在 Python3 中我可以做到:

    In [224]: txt = "Côte d'Ivoire"
    In [225]: x = np.zeros((2,),dtype='U20')
    In [226]: x[0] = txt
    In [227]: x
    Out[227]: 
    array(["Côte d'Ivoire", ''],   dtype='<U20')
    

    这意味着我可能可以打开一个“UTF-8”文件(常规,而不是字节模式)和 readlines,并将它们分配给像 x 这样的数组元素。

    genfromtxt 坚持使用无法处理较大的UTF-8 集合(7 字节v 8)的字节字符串(ascii)进行操作。所以我需要在某个时候申请decode 以获得U 数组。

    我可以使用genfromtxt 将其加载到“S”数组中:

    In [258]: txt="Côte d'Ivoire"
    In [259]: a=np.genfromtxt([txt.encode()],delimiter=',',dtype='S20')
    In [260]: a
    Out[260]: 
    array(b"C\xc3\xb4te d'Ivoire",  dtype='|S20')
    

    并将decode 应用于单个元素:

    In [261]: print(a.item().decode())
    Côte d'Ivoire
    
    In [325]: print _
    Côte d'Ivoire
    

    或使用np.char.decode 将其应用于数组的每个元素:

    In [263]: np.char.decode(a)
    Out[263]: 
    array("Côte d'Ivoire", dtype='<U13')
    In [264]: print(_)
    Côte d'Ivoire
    

    genfromtxt 让我指定converters

    In [297]: np.genfromtxt([txt.encode()],delimiter=',',dtype='U20',
        converters={0:lambda x: x.decode()})
    Out[297]: 
    array("Côte d'Ivoire", dtype='<U20')
    

    如果csv 混合了字符串和数字,则此converters 方法将比np.char.decode 更易于使用。只需为每个字符串列指定转换器即可。

    (请参阅我之前对 Python2 尝试的编辑)。

    【讨论】:

    • 不是 OP,但感谢您提供清晰而有用的答案。
    • 感谢您的回答。有用!我刚开始使用 Python,我发现 numpy 无法开箱即用地读取 UTF-8 很奇怪。我读过 Python 很简单,并且在开发时考虑到了简单性和易用性,但阅读 UTF-8 需要额外的转换?我以为我们生活在 2015 年。
    猜你喜欢
    • 2018-05-17
    • 2015-04-12
    • 1970-01-01
    • 2018-07-18
    • 2014-04-18
    • 2017-01-27
    相关资源
    最近更新 更多