krs*_*shk 12 python numpy python-3.4
我试图从文本文件创建一个数组.我之前看到numpy有一个方法loadtxt
,所以我尝试了,但它在每行之前添加了一些垃圾字符......
# my txt file
.--``--.
.--` `--.
| |
| |
`--. .--`
`--..--`
# my python v3.4 program
import numpy as np
f = open('tile', 'r')
a = np.loadtxt(f, dtype=str, delimiter='\n')
print(a)
# my print output
["b' .--``--. '"
"b'.--` `--.'"
"b'| |'"
"b'| |'"
"b'`--. .--`'"
"b' `--..--` '"]
Run Code Online (Sandbox Code Playgroud)
这些'b'和双引号是什么?它们来自哪里?我试过从互联网上挑选一些解决方案,比如用编解码器打开文件,用'S20','S11'改变dtype,还有很多其他不起作用的东西......我期待的是一个unicode字符串数组看起来像这样:
[[' .--``--. ']
['.--` `--.']
['| |']
['| |']
['`--. .--`']
[' `--..--` ']]
Run Code Online (Sandbox Code Playgroud)
信息:我正在使用debian稳定存储库中的python 3.4和numpy
hpa*_*ulj 14
np.loadtxt
并np.genfromtxt
以字节模式运行,这是Python 2中的默认字符串类型.但是Python 3使用unicode,并用此标记字节串b
.
我在python3 ipython
会话中尝试了一些变化:
In [508]: np.loadtxt('stack33655641.txt',dtype=bytes,delimiter='\n')[0]
Out[508]: b' .--``--.'
In [509]: np.loadtxt('stack33655641.txt',dtype=str,delimiter='\n')[0]
Out[509]: "b' .--``--.'"
...
In [511]: np.genfromtxt('stack33655641.txt',dtype=str,delimiter='\n')[0]
Out[511]: '.--``--.'
In [512]: np.genfromtxt('stack33655641.txt',dtype=None,delimiter='\n')[0]
Out[512]: b'.--``--.'
In [513]: np.genfromtxt('stack33655641.txt',dtype=bytes,delimiter='\n')[0]
Out[513]: b'.--``--.'
Run Code Online (Sandbox Code Playgroud)
genfromtxt
与dtype=str
给出最干净显示-除了它去除空白.我可能不得不使用转换器将其关闭.这些函数用于读取csv
数据,其中(白色)空格是分隔符,而不是数据的一部分.
loadtxt
和genfromtxt
超过杀简单的文字是这样的.普通文件读取很好:
In [527]: with open('stack33655641.txt') as f:a=f.read()
In [528]: print(a)
.--``--.
.--` `--.
| |
| |
`--. .--`
`--..--`
In [530]: a=a.splitlines()
In [531]: a
Out[531]:
[' .--``--.',
'.--` `--.',
'| |',
'| |',
'`--. .--`',
' `--..--`']
Run Code Online (Sandbox Code Playgroud)
(我的文本编辑器设置为去除尾随空白,因此是粗糙的行).
@DSM's
建议:
In [556]: a=np.loadtxt('stack33655641.txt',dtype=bytes,delimiter='\n').astype(str)
In [557]: a
Out[557]:
array([' .--``--.', '.--` `--.', '| |',
'| |', '`--. .--`', ' `--..--`'],
dtype='<U16')
In [558]: a.tolist()
Out[558]:
[' .--``--.',
'.--` `--.',
'| |',
'| |',
'`--. .--`',
' `--..--`']
Run Code Online (Sandbox Code Playgroud)
小智 7
Python3 正在使用 Unicode。使用loadtxt
with时我遇到了同样的问题dtype='S'
。但是在两者中使用dtype='U
as或,它会给出没有Unicode string
numpy.loadtxt
numpy.genfromtxt
b
a=numpy.loadtxt('filename',dtype={'names':('col1','col2','col3'),'formats':('U10','U10','i4')},delimiter=',')
print(a)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
15437 次 |
最近记录: |