对于一个类,我必须编写一个函数,它采用 03:12:19 形式的时间(换句话说,三小时十二分十九秒)并将它们转换为相应的秒数。我已经开始但似乎无法让数学工作,这是我目前拥有的代码:
def secs(timestr):
import re
timexp = re.compile('(\d\d):(\d\d):(\d\d)')
calc = re.sub(timexp,r'int(\1)*3600+int(\2*60)+int(\3)',timestr)
return print(calc)
str = '03:20:13'
secs(str)
我搞砸了删除 r 但它给了我一个奇怪的结果。帮助?
请您参考如下方法:
正则表达式对于解析输入字符串来说可能有点矫枉过正,而且完全是计算总秒数的错误工具。这是一个简单的替换:
def secs(timestr):
hours, minutes, seconds = timestr.split(':')
return int(hours) * 3600 + int(minutes) * 60 + int(seconds)
这不会处理错误检查(不是正确数量的“:”分隔符、非数字内容等),但您原来的正则表达式方法也不会。如果您确实需要完整性检查输入,我会这样做:
def secs(timestr):
timeparts = timestr.split(':')
if len(timeparts) == 3 and all((part.isdigit() for part in timeparts)):
return int(timeparts[0]) * 3600 + int(timeparts[1] * 60 + int(timeparts[2])
else:
# not a matching string - do whatever you like.
return None
还有其他方法。
如果您想要一个字符串而不是整数来表示秒数,返回 str(int(hours) * 3600 + int(minutes) * 60 + int(seconds))。
编辑:响应“我被指示用正则表达式替换来做这件事,所以这是我必须做的”:
re.sub可以采用两种不同的替换参数。您可以提供字符串模式或函数来计算替换字符串。字符串模式不进行数学运算,因此您必须使用函数。
If repl is a function, it is called for every non-overlapping occurrence of pattern. The function takes a single match object argument, and returns the replacement string.
def _calculate_seconds(timematch):
return str(int(timematch.group(1)) * 3600 + int(timematch.group(2)) * 60 + int(timematch.group(3)))
def secs(timestr):
timexp = re.compile(r'(\d{1,2}):(\d{1,2}):(\d{1,2})')
return re.sub(timexp, _calculate_seconds, timestr)
但这是一种糟糕的方法,除非您尝试将多次出现的这些时间模式转换为单个较大的字符串。
在这里编译正则表达式并不是真正必要的,甚至没有帮助,因为每次调用该函数时都需要重做。通常的方法是在函数外编译它 - 但作为 regexp docs注意:
The compiled versions of the most recent patterns passed to re.match(), re.search() or re.compile() are cached, so programs that use only a few regular expressions at a time needn’t worry about compiling regular expressions.
不过,养成一个好习惯。只是不在像这样的局部函数定义中。
