【问题标题】:Parsing 'time string' with Python?用 Python 解析“时间字符串”?
【发布时间】:2010-09-09 20:26:27
【问题描述】:

我正在编写一个应用程序,让用户按以下格式输入时间:

1m30s # 1 Minute,  30 Seconds

3m15s # 3 Minutes, 15 Seconds

2m25s # 2 Minutes, 25 Seconds

2m    # 2 Minutes

55s   # 55 Seconds

数据可以有一个“分钟名称”、一个“秒名称”,或两者兼有。将这些字符串解析为类似于以下格式的正确方法是什么:

{
    "minutes" : 3
    "seconds" : 25
}

【问题讨论】:

    标签: python string


    【解决方案1】:
    import re
    
    tests=['1m30s','3m15s','2m25s','2m','55s']
    for time_str in tests:
        match=re.match('(?:(\d*)m)?(?:(\d*)s)?',time_str)
        if match:
            minutes = int(match.group(1) or 0)
            seconds = int(match.group(2) or 0)
            print({'minutes':minutes,
                   'seconds':seconds})
    
    # {'seconds': 30, 'minutes': 1}
    # {'seconds': 15, 'minutes': 3}
    # {'seconds': 25, 'minutes': 2}
    # {'seconds': 0, 'minutes': 2}
    # {'seconds': 55, 'minutes': 0}
    

    【讨论】:

      【解决方案2】:

      正则表达式助你一臂之力!

      >>> import re
      >>> minsec = re.compile(r'(?P<minutes>\d+)m(?P<seconds>\d+)s')
      >>> result = minsec.match('1m30s')        
      >>> result.groupdict()
      {'seconds': '30', 'minutes': '1'}
      

      编辑:这是修改后的解决方案:

      import re
      pattern = r'(?:(?P<minutes>\d+)m)?(?:(?P<seconds>\d+)s)?'
      
      minsec = re.compile(pattern)
      
      def parse(s, pat=minsec):
          return pat.match(s).groupdict()
      
      tests = ['1m30s', '30s', '10m29s']
      for t in tests:
          print '---'
          print ' in:', t
          print 'out:', parse(t)
      

      输出:

      ---
       in: 1m30s
      out: {'seconds': '30', 'minutes': '1'}
      ---
       in: 30s
      out: {'seconds': '30', 'minutes': None}
      ---
       in: 10m29s
      out: {'seconds': '29', 'minutes': '10'}
      

      【讨论】:

      • 不错!我正在做类似的回应,但你的更好。我从来不知道这样命名匹配组。
      猜你喜欢
      • 2012-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多