我有一个包含警报发生时间的文件。我想按升序对它们进行排序。你能帮我指导一下吗?
采样时间格式。
1 day, 19 hours
3 weeks
4 weeks, 1 day
2 minutes
1 month, 1 week
10 hours, 36 minutes
4 weeks, 1 day
4 weeks, 1 day
13 minutes
5 hours, 16 minutes
1 hour, 53 minutes
3 hours, 18 minutes
21 hours, 42 minutes
18 hours, 49 minutes
21 hours, 43 minutes
答案 0 :(得分:2)
也许不是超级优雅,但可以直接在Python中使用:
#!/usr/bin/env python
import operator
# 1 month = 28-31 days and 4 weeks = 28 days, so month is kept separate
time_in_seconds = {
'week': 7*24*60*60,
'day': 24*60*60,
'hour': 60*60,
'minute': 60,
'second': 1
}
if __name__ == '__main__':
times = []
with open('sample_time.txt', 'r') as f:
for line in f.read().split('\n'):
months = 0
seconds = 0
try:
for pair in line.split(', '):
num, denum = pair.split(' ')
if denum.startswith('month'):
months += int(num)
else:
seconds += time_in_seconds[denum.rstrip('s')]*int(num)
times.append([months, seconds, line])
except:
pass
sorted_times = sorted(times, key=operator.itemgetter(0,1))
for line in map(operator.itemgetter(2), sorted_times):
print(line)
假定您的文件名为sample_time.txt
。