0

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

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

4

4 回答 4

5

好吧,如果您只想要秒,并且不太担心小时在分钟之前,分钟在秒之前,只要它们是合格的(即 '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
于 2012-10-22T21:14:45.967 回答
2

如果数据与您的示例中一样,您可以简单地执行以下操作:

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]
于 2012-10-22T20:58:31.783 回答
1

试试这个:

[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

刚刚意识到您并不是在每个输入上都在寻找三倍。现在修好了。

于 2012-10-22T20:59:11.267 回答
0

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
于 2012-10-22T21:30:17.073 回答