我有点熟悉np.fromregex格式. 我阅读了教程,并试图实现它来读取数据文件。你知道吗
当使用简单的python列表理解读取文件时,它会给出所需的结果:
[400, 401, 405, 408, 412, 414, 420, 423, 433]
。你知道吗
但是,当np.fromregex
给出另一个格式答案时:
[(400,) (401,) (405,) (408,) (412,) (414,) (420,) (423,) (433,)]
。你知道吗
如何更改代码,使regex的答案与简单的python for循环相同。你知道吗
谢谢。你知道吗
我知道这是一个简单的问题,但我花了很多时间去寻找 解决方案和它可能对其他人也有好处,并节省一些时间。你知道吗
相关链接:
https://docs.scipy.org/doc/numpy/reference/generated/numpy.fromregex.html
np.fromregex with string as dtype
from __future__ import print_function, division, with_statement, unicode_literals
import numpy as np
import re
data = """
DMStack failed for: lsst_z1.0_400.fits
DMStack failed for: lsst_z1.0_401.fits
DMStack failed for: lsst_z1.0_405.fits
DMStack failed for: lsst_z1.0_408.fits
DMStack failed for: lsst_z1.0_412.fits
DMStack failed for: lsst_z1.0_414.fits
DMStack failed for: lsst_z1.0_420.fits
DMStack failed for: lsst_z1.0_423.fits
DMStack failed for: lsst_z1.0_433.fits
"""
ifile = 'a.txt'
with open(ifile, 'w') as fo:
fo.write(data.lstrip())
# regex
regexp = r".*_(\d+?).fits"
# This works fine
ans = [int(re.findall(regexp, line)[0]) for line in open(ifile)]
print(ans)
# using fromregex
dt = [('num', np.int32)]
x = np.fromregex(ifile, regexp, dt)
print(x)
更新
当我使用将来的导入时,上面的代码失败了。错误日志如下:
Traceback (most recent call last):
File "a.py", line 31, in <module>
x = np.fromregex(ifile, regexp, dt)
File "/Users/poudel/miniconda2/lib/python2.7/site-packages/numpy/lib/npyio.py", line 1452, in fromregex
dtype = np.dtype(dtype)
TypeError: data type not understood
$ which python
python is /Users/poudel/miniconda2/bin/python
$ python -c "import numpy; print(numpy.__version__)"
1.14.0
我不知道这样做没有一个循环。你知道吗
感谢@zipa和@hpaulj,终于有了这段代码 python2和将来的陈述。它也适用于python3。你知道吗
我们需要使用
dt = [(str('num'), np.int32)]
,而不是dt = [('num', np.int32)]
。你知道吗只要选择小组,你就会得到你想要的:
相关问题 更多 >
编程相关推荐