【发布时间】:2015-10-08 11:45:16
【问题描述】:
我有一个日期格式为“1:*?year mo da ho mi se.condsdec”的文件(其中“?”是 1 个字符的通配符)即:
*A 2014 12 31 23 59 59.123456
我想将其提取为字符串(最终转换为日期时间字符串)。
我可以使用正则表达式模式将日期提取为一组int/floats:
time_pattern=r'\*.{2}(\d{4}) (\d{2}) (\d{2}) (\d{2}) (\d{2}) (\d{2}\.\d{8})'
但不是字符串。如何使用字符串使其工作?
我正在使用 python 3.4.3 和 numpy 1.9.3。
import numpy as np
time_pattern=r'\*.{2}(\d{4}) (\d{2}) (\d{2}) (\d{2}) (\d{2}) (\d{2}\.\d{8})'
t_dtype=[('year',np.int16),('month',np.int8),('day',np.int8),\
('hour',np.int8),('min',np.int8),('sec',np.float64)]
out=np.fromregex('filename',time_pattern,t_dtype)
print(out)
#returns [(2013, 11, 26, 0, 0, 10.0) (2013, 11, 26, 0, 0, 20.0)
# (2013, 11, 26, 0, 0, 30.0)]
basic_t=r'$\*.{2}(.{28})'
t_dtype=[('date',str)]
out=np.fromregex('filename',basic_t,t_dtype)
#causes TypeError:
#TypeError: Empty data-type
使用文件filename:
* 2003 11 26 00 00 10.00000000
some text or interesting data
* 2003 11 26 00 00 20.00000000
more text
even more text
* 2003 11 26 00 00 30.00000000
etc.
编辑:注意模式中的简单
with open(file) as f:
for line in f:
m=re.search(basic_t,line)
但我希望将输出作为一个 numpy 数组,并希望将运行时间保持在最低限度。
编辑编辑:
将 dtype 更改为 'S' 或 np.str 可以消除错误,但我仍然得到一个空列表作为输出
【问题讨论】:
-
如果我这样做,我似乎会得到空字符串作为输出。 IE。如果我将年份和月份设为
np.str,我会得到类似('', '', 26, 0, 0, 10.0)的输出