1m2s100msみたいな表示をミリ秒単位に

メモ

所要時間を3m10s48msみたいに表示するプログラムがいて(やめてほしい)、この値をミリ秒に変換したい。

こんな感じかな〜?

(2015-03-09) ダメだったので直しました。正規表現は苦手だ

#!/usr/bin/python

"""
Convert a time string like 1h2m3s4ms5us6ns to millisecond value.
"""

import sys
import re

for line in sys.stdin:
    # (RE of unit string, millisec value per a unit)
    units = [(r'(h|hours?)', 3600000),
             (r'(m|min|minutes?)', 60000),
             (r'(s|sec|seconds?)', 1000),
             (r'(ms|msec|millisec|milliseconds?)', 1),
             (r'(us|usec|microsec|microseconds?)', 0.001),
             (r'(ns|nsec|nanosec|nanoseconds?)', 0.000001)]

    time = 0
    ok = False
    for unit in units:
        pattern = r'(\d+\.*\d*)\s*' + unit[0] + r'(\d|\s)'
        matched = re.search(pattern, line)
        if matched:
            try:
                num = int(matched.group(1))
            except ValueError:
                num = float(matched.group(1))
            time += num * unit[1]
            ok = True

    if not ok:
       raise ValueError("No pattern matched.")
    print time