【问题标题】:Genfromtext Issues with umlautsGenfromtxt 变音符号的问题
【发布时间】:2018-09-06 09:41:03
【问题描述】:

我只是在编写一个有趣的程序,但遇到了一个我无法找到解决方案的问题。 我写的代码是这样的:

import numpy as np

data= np.genfromtxt('list.txt', unpack=True, dtype=("U12", "U12"))
print(data)

'list.txt' 看起来像这样:

# random random2
foo ßaar

当我尝试运行此代码时,出现以下错误消息:

UnicodeDecodeError Traceback(最近一次调用最后一次) C:\Users\syhon\Documents\Test\test.py in () 1 将 numpy 导入为 np 2 ----> 3 data= np.genfromtxt('list.txt', unpack=True, dtype=("U12", "U12")) 4 打印(数据)

C:\Users\syhon\Anaconda3\lib\site-packages\numpy\lib\npyio.py in >genfromtxt(fname, dtype, cmets, delimiter, skip_header, skip_footer, >converters, missing_values,filling_values, usecols,名称、排除列表、>deletechars、replace_space、autostrip、区分大小写、defaultfmt、解包、>usemask、松散、invalid_raise、max_rows) 1927 dtype = np.dtype(ttype) 1928 # -> 1929 输出 = np.array(数据,dtype) 1930 如果使用掩码: 1931 如果 dtype.names:

UnicodeDecodeError:“ascii”编解码器无法解码位置 0 中的字节 0xc3:序数不在范围内(128)

但是,只要我删除 ß,代码就可以正常工作。 有没有办法保留变音符号?

【问题讨论】:

    标签: python genfromtxt


    【解决方案1】:

    您可以尝试手动指定编码吗?

    >>> import numpy as np
    >>> data= np.genfromtxt('list.txt', unpack=True, dtype=("U12", "U12"), encoding='ascii')
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "L:\lib\site-packages\numpy\lib\npyio.py", line 1708, in genfromtxt
        first_line = _decode_line(next(fhd), encoding)
      File "L:\\lib\encodings\ascii.py", line 26, in decode
        return codecs.ascii_decode(input, self.errors)[0]
    UnicodeDecodeError: 'ascii' codec can't decode byte 0xdf in position 4: ordinal not in range(128)
    >>> data= np.genfromtxt('list.txt', unpack=True, dtype=("U12", "U12"), encoding='bytes')
    >>> print(data)
    ['foo' 'ßaar']
    

    注意:对我来说bytes 已经是默认编码,所以我最初无法复制您的错误。

    编辑:澄清一下,我的意思是将encoding 关键字参数添加到np.genfromtxt() 函数调用中。当我最初运行您的代码时,没有错误。我只能在将编码设置为ascii 时重现您的错误。

    【讨论】:

    • 两个文件都使用 UTF-8 编码(希望这就是你的意思)。如果重要的话,我的 Python 版本是 3.6.1
    • 我没有在我的代码中指定编码。但是,当我尝试这样做时,会出现以下错误消息:“TypeError: genfromtxt() got an unexpectetd keyword argument 'encoding'.
    【解决方案2】:

    # -*- coding: utf-8 -*-
    

    在顶行似乎解决了问题

    【讨论】:

      猜你喜欢
      • 2016-05-03
      • 1970-01-01
      • 2012-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多