繁体   English   中英

在python中从H mn s格式时间中提取值

[英]Extract values from H mn s format time in python

我想使用一些正则表达式从时间值中提取此类数据:

1h 34mn 2s     >>> [1,34,2]
1h 4mn         >>> [1,4]
34mn 2s        >>> [34,2]
34s            >>> [34]

我试过了

re.match(r'((.*)h)?((.*)mn)?((.*)s)?', '1h 34mn').groups()
('1h', '1', ' 34mn', ' 34', None, None)

差不多完成了,但仍然不是我想要的。

编辑:

我需要以秒为单位提取总值1h 34mn 2s >>> 1*3600+34*60+2

好吧,如果您只想要秒,而不必担心小时在分钟之前,分钟在秒之前,只要它们是合格的(即“ 1s 9h 32m”有效),则可以使用:

import re

mult = {'h': 60*60, 'mn': 60}
res = sum(int(num) * mult.get(val, 1) for num, val in re.findall('(\d+)(\w+)', '1h 34mn 2s'))
# 5642

如果数据如您的示例中所示,则只需执行以下操作:

In [171]: import re

In [172]: s='1h 34mn 2s'

In [173]: re.findall('\d+',s)
Out[173]: ['1', '34', '2']

或者如果您想要int的:

In [175]: [int(i)for i in re.findall('\d+',s)]
Out[175]: [1, 34, 2]

尝试这个:

[in] regex = re.compile(r'^(?:(\d+)h)?(?: *)(?:(\d+)mn)?(?: *)(?:(\d+)s)?$')
[in] for x in ("1h 34mn 2s", "1h 4mn", "34mn 2s", "34s"):
[in]     hours, minutes, seconds = regex.match(x).groups()
[in]     total = 0
[in]     if hours:
[in]         total += int(hours) * 3600
[in]     if minutes:
[in]         total += int(minutes) * 60
[in]     if seconds:
[in]         total += int(seconds)
[in]     print total

[out] 5642
[out] 3840
[out] 2042
[out] 34

只是意识到您并没有在每个输入中寻找三元组。 立即修复。

import re

a = ['1h 34mn 2s','1h 4mn','34mn 2s','34s']

def convert(s):
    if s:
        return int(s[0])
    else:
        return 0

def get_time(a):
    h = convert(re.findall('(\d*)h',a))
    m = convert(re.findall('(\d*)m',a))
    s = convert(re.findall('(\d*)s',a))
    return h,m,s

for i in a:
    print get_time(i)

输出:

(1, 34, 2)
(1, 4, 0)
(0, 34, 2)
(0, 0, 34)

编辑。 我刚刚看到,您想要几秒钟的日期。 您只需将get_time函数中的返回行编辑为:

return h*3600+m*60+s

输出:

5642
3840
2042
34

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM