我正在尝试将文本文件中的所有时间戳(形式为’HH:MM:SS’)增加一个命令行参数指定给我程序的秒数.
这是迄今为止我的努力的简化版本:
import re from datetime import datetime,timedelta time_diff = timedelta(seconds=10) def replace_time(matchobj): if matchobj.group(1) not in [None,'']: return (datetime.strptime(matchobj.group(1),"%H:%M:%S") + time_diff).strftime("%H:%M:%S") print re.sub('(\d\d:\d\d:\d\d)',replace_time,"01:27:55")
这很好用:运行它的结果是01:28:05这正是我想要的.
但是,我听说我应该尽可能少地使用全局变量.所以我想知道是否有一种简单的方法可以将time_diff作为参数传递给replace_time而不是使用全局变量.
我尝试了显而易见的,但它失败了:
def replace_time(matchobj,time_diff): if matchobj.group(1) not in [None,"%H:%M:%S") + time_diff).strftime("%H:%M:%S") time_diff = timedelta(seconds=10) print re.sub('(\d\d:\d\d:\d\d)',replace_time(matchobj,time_diff),"01:27:55")
出现此错误:NameError:未定义名称“matchobj”,因此我无法直接传递matchobj.
我看过standard re page和standard re howto,但找不到我需要的信息.我怎样才能避免在这里使用全局变量?我可以以某种方式将额外的参数传递给replace_time函数吗?提前致谢.
解决方法
你可以在一个闭包中包装一个函数,如下所示:
def increment_by(time_diff): def replace_time(matchobj): if matchobj.group(1) not in [None,'']: return (datetime.strptime(matchobj.group(1),"%H:%M:%S") + time_diff).strftime("%H:%M:%S") return replace_time time_diff = timedelta(seconds=10) print re.sub('(\d\d:\d\d:\d\d)',increment_by(time_diff),"01:27:55")
或者您可以像这样使用stdlib中的部分:
from functools import partial def replace_time(time_diff,matchobj): if matchobj.group(1) not in [None,'']: return (datetime.strptime(matchobj.group(1),partial(replace_time,"01:27:55")