Python 将字符串小时分钟转换为分钟
问题描述:
所以说我有一个这样的列表:
So say I have a list like so:
runtimes = ['24 min per ep',
'1 hr 55 min',
'24 min per ep',
'25 min per ep',
'23 min per ep',
'23 min per ep',
'23 min per ep',
'27 min per ep',
'24 min per ep',
'23 min per ep',
'24 min',
'22 min per ep',
'25 min per ep',
'24 min per ep',
'23 min per ep',
'24 min per ep',
'24 min per ep',
'24 min per ep',
'24 min per ep',
'1 hr 41 min',
'1 hr 27 min',
'25 min per ep',
'1 hr 22 min',
'30 min per ep',
'25 min per ep',
'1 hr 31 min',
'2 hr 4 min',
'24 min per ep',
'24 min per ep']
我想将这些值转换为纯分钟:
I want to convert these values into purely minutes:
我首先认为最好使用如下两个正则表达式将1 小时"替换为60 分钟",然后删除所有非数字,但这似乎并不理想.
I first thought it would be best to use two regex expressions like the ones below to replace the "1 hr" with "60 min" and then remove all the non-numerics, but this does not seem ideal.
re.sub("1 hr", "60 min", runtimes))
re.sub("\D", "", runtimes)
如果有人知道更好的方法,将不胜感激.
If someone knows a better way to do this it would be greatly appreciated.
如果您还有其他问题,请告诉我.
Please let me know if you have any more questions.
感谢您的帮助.
答
这很简单,无需使用任何特殊类型的解析器即可进行编码:
This is fairly simple just to code without using any special kind of parser:
def parse_runtime(runtime):
mins = 0
fields = runtime.split()
for idx in range(0, len(fields)-2):
if fields[idx+1] in ('min', 'mins', 'minutes'):
mins += int(fields[idx])
elif fields[idx+1] in ('hr', 'hrs', 'hours'):
mins += int(fields[idx]) * 60
return mins
runtime_mins = []
for runtime in runtimes:
try:
mins = parse_runtime(runtime)
runtime_mins.append(mins)
except ValueError:
print('Bad runtime: ' + runtime)
print(runtime_mins)