我想从字符串中提取日期信息。字符串可能如下所示:
我想摘录:
我开始这样做:
publishedWhen = '1 year 1 month and 1 days and 1 hour'
y,m,d,h = 0,0,0,0
if 'day ' in publishedWhen:
d = int(publishedWhen.split(' day ')[0])
if 'days ' in publishedWhen:
d = int(publishedWhen.split(' days ')[0])
if 'days ' not in publishedWhen and 'day ' not in publishedWhen:
d = 0
if 'month ' in publishedWhen:
m = int(publishedWhen.split(' month ')[0])
d = int(publishedWhen.replace(publishedWhen.split(' month ')[0] + ' month ','').replace('and','').replace('days','').replace('day',''))
if 'months ' in publishedWhen:
m = int(publishedWhen.split(' months ')[0])
不过,我知道这段代码有很多bug(有些情况可能没有考虑在内),而且regex可能会产生一些更干净、更有效的代码。这是真的吗?哪个正则表达式可以帮我提取所有这些信息
您可以don't have to use re\gular expres{2}ions?并在Python包索引中查看非常丰富的第三方包库
例如,您可以将^{} -用于解析人类可读的日期,将
dateutil
-用于relative delta object的组合:印刷品:
我并不特别喜欢需要用一些基本日期来做delta,并且非常确定有一个包可以直接解析到delta对象中。愿意接受任何建议
相关问题 更多 >
编程相关推荐