【问题标题】:np.fromregex with string as dtypenp.fromregex 与字符串作为 dtype
【发布时间】: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)的输出

标签: python regex numpy


【解决方案1】:

您的问题是您将 dtype 设置为 int 或 float,而您应该将它们指定为 np.str_。你还需要指定字符串的长度,所以

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.str_,4),('month',np.str_,2),('day',np.str_,2),\
('hour',np.str_,2),('min',np.str_,2),('sec',np.str_,3)]

out=np.fromregex('filename',time_pattern,t_dtype)
print(out)

如果您查看this 的第二个示例,它显示了如何处理字符串

【讨论】:

    猜你喜欢
    • 2013-02-17
    • 1970-01-01
    • 2021-12-13
    • 2014-04-03
    • 2018-12-10
    • 1970-01-01
    • 2016-01-22
    • 2019-03-28
    • 2014-03-24
    相关资源
    最近更新 更多