回答此问题可获得 20 贡献值,回答如果被采纳可获得 50 分。
<p>我有点熟悉np.fromregex格式. 我阅读了教程,并试图实现它来读取数据文件。你知道吗</p>
<p>当使用简单的python列表理解读取文件时,它会给出所需的结果:
<code>[400, 401, 405, 408, 412, 414, 420, 423, 433]</code>。你知道吗</p>
<p>但是,当<code>np.fromregex</code>给出另一个格式答案时:
<code>[(400,) (401,) (405,) (408,) (412,) (414,) (420,) (423,) (433,)]</code>。你知道吗</p>
<p>如何更改代码,使regex的答案与简单的python for循环相同。你知道吗</p>
<p>谢谢。你知道吗</p>
<p>我知道这是一个简单的问题,但我花了很多时间去寻找
解决方案和它可能对其他人也有好处,并节省一些时间。你知道吗</p>
<p>相关链接:<br/>
<a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.fromregex.html" rel="nofollow noreferrer">https://docs.scipy.org/doc/numpy/reference/generated/numpy.fromregex.html</a><br/>
<a href="https://stackoverflow.com/questions/33014828/np-fromregex-with-string-as-dtype">np.fromregex with string as dtype</a></p>
<pre><code>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)
</code></pre>
<p><strong>更新</strong><br/>
当我使用将来的导入时,上面的代码失败了。错误日志如下:</p>
<pre><code>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
</code></pre>