【问题标题】:Converting bytes read from a file using numpy fromfile to unicode in Python 3在 Python 3 中将使用 numpy fromfile 从文件读取的字节转换为 unicode
【发布时间】:2014-10-15 13:04:11
【问题描述】:

我正在尝试在 Python 3 中使用 NumPy fromfile 从文件中读取一串字节。我的目标是将字节转换为普通的 Python 3 字符串。例如:

$ echo "1234" > t.txt

现在文件 t.txt 包含 4 个字节的文本。那么:

import numpy as np

values=np.fromfile('t.txt',dtype='|S1',count=4)
print ("values={}".format(values))
values=np.fromfile('t.txt',dtype='|U1',count=4)
print ("values={}".format(values))

给予:

values=[b'1' b'2' b'3' b'4']
Traceback (most recent call last):
  File "./t.py", line 12, in <module>
    print ("values={}".format(values))
  File "/home/hakon/.pyenv/versions/3.4.2/lib/python3.4/site-packages/numpy/core/numeric.py", line 1715, in array_str
    return array2string(a, max_line_width, precision, suppress_small, ' ', "", str)
  File "/home/hakon/.pyenv/versions/3.4.2/lib/python3.4/site-packages/numpy/core/arrayprint.py", line 454, in array2string
    separator, prefix, formatter=formatter)
  File "/home/hakon/.pyenv/versions/3.4.2/lib/python3.4/site-packages/numpy/core/arrayprint.py", line 328, in _array2string
    _summaryEdgeItems, summary_insert)[:-1]
  File "/home/hakon/.pyenv/versions/3.4.2/lib/python3.4/site-packages/numpy/core/arrayprint.py", line 500, in _formatArray
    word = format_function(a[-1])
UnicodeDecodeError: 'utf-32-le' codec can't decode bytes in position 0-3: codepoint not in range(0x110000)

我想获得一个普通的 Python 3 字符串,例如 values='1234'。如何做到这一点?

【问题讨论】:

  • 如果你使用dtype='|S4'会怎样?

标签: python python-3.x numpy


【解决方案1】:

您可以使用astype 将字节转换为str:

import numpy as np

values = np.fromfile('t.txt',dtype='|S1',count=4).astype('|U1')
print(values)
# ['1' '2' '3' '4']

print(values.view('|U4'))
# ['1234']

print(values.dtype)
# <U1

【讨论】:

  • 这里有一个替代方案:np.fromfile('t.txt',dtype='int8',count=4).tostring().decode()
【解决方案2】:

我知道问题明确要求np.fromfile,但为什么不直接使用内置文件接口呢?

f = open('t.txt', 'r')
values = f.read().rstrip('\n')
f.close()

注意:Python 3 字符串默认为 Unicode。

【讨论】:

  • 感谢您的建议!
猜你喜欢
  • 2018-11-25
  • 2018-04-29
  • 2018-08-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-27
  • 1970-01-01
  • 2014-01-27
相关资源
最近更新 更多