【问题标题】:How to use regular expressions in an if statement, python 3如何在if语句中使用正则表达式,python 3
【发布时间】:2018-09-30 21:58:26
【问题描述】:

编辑:看来我的错误是由我的一个简单的疏忽引起的,应该是在 python 中。感谢大家的帮助!

我正在尝试自学 Python,因此我想制作一个简单的脚本来计算我在当前工作中的工作时间。似乎我找不到任何关于如何在条件 if 和 elif 语句中使用正则表达式的好资料。

我要做的是检查我的开始时间是否有上午或下午,以及我的结束时间是否有上午或下午,这取决于我可以准确添加总小时数的组合.

为此,我使用正则表达式来检查我输入的结束时间是上午还是下午。然后我看看我发送的时间有哪个组合, 例如start_time = 8:00am 和 end_time = 11:23am 所以这应该匹配 start_match_am 和 end_match_am

我的完整代码如下:

import re
pattern = re.compile('^([0-1]?[0-9]):[0-5][0-9][aApPmM]{2}$')
start_time = ""
end_time = ""
hours_worked = 0.0

start_time = input("Please enter the time you started working(ex -- 8:00am): \n")
while re.match(pattern, start_time) == False:
    print("I'm sorry the time must be in the format -- HH:MMam or H:MMpm \n")
    start_time = input("Please enter the time you started working(ex -- 8:00am): \n")
end_time = input("Please enter the time you stopped working(ex -- 5:00pm): \n")
while re.match(pattern, end_time) == False:
    print("I'm sorry the time must be in the format -- HH:MMam or H:MMpm \n")
    end_time = input("Please enter the time you stopped working(ex -- 8:00am): \n")
start_hour = int(start_time[:(start_time.find(':'))])
start_minutes = int(start_time[(start_time.find(':') + 1):-2])
end_hour = int(end_time[:(end_time.find(':'))])
end_minutes = int(end_time[(end_time.find(':') + 1):-2])
start_period = start_time[start_time.find(':')+3:]
end_period = end_time[end_time.find(':')+3:]
pattern_am = re.compile('am', re.I)
pattern_pm = re.compile('pm', re.I)
start_match_am = re.match(pattern_am, start_period)
start_match_pm = re.match(pattern_pm, start_period)
end_match_am = re.match(pattern_am, end_period)
end_match_pm = re.match(pattern_pm, end_period)
if start_match_am is not None & end_match_am is not None:
    total_hours = end_hour - start_hour
    total_minutes = (end_minutes - start_minutes+60) % 60
    print("You worked for "+total_hours+"hr "+total_minutes+"min")
elif start_match_pm is not None & end_match_pm is not None:
    total_hours = end_hour - start_hour
    total_minutes = (end_minutes - start_minutes+60) % 60
    print("You worked for "+total_hours+"hr "+total_minutes+"min")
elif start_match_am is not None & end_match_pm is not None:
    total_hours = end_hour + 12 - start_hour
    total_minutes = (end_minutes - start_minutes + 60) % 60
    print("You worked for "+total_hours+"hr "+total_minutes+"min")
elif start_match_pm is not None & end_match_am is not None:
    total_hours = end_hour + 12 - start_hour
    total_minutes = (end_minutes - start_minutes + 60) % 60
    print("You worked for "+total_hours+"hr "+total_minutes+"min")

首先我想说我知道我现在不能正确地把分钟加在一起,我在我很累的时候写了这个,当我让正则表达式工作时会修复。这个问题具体发生在这一行:

if start_match_am is not None & end_match_am is not None:

我得到的错误是:

Please enter the time you started working(ex -- 8:00am): 
8:00am
Please enter the time you stopped working(ex -- 5:00pm): 
11:23am
Traceback (most recent call last):
  File "/home/primus/PycharmProjects/HoursWorks/venv/HoursWorked/CalculateHours.py", line 27, in <module>
    if start_match_am is not None & end_match_am is not None:
TypeError: unsupported operand type(s) for &: 'NoneType' and '_sre.SRE_Match'

Process finished with exit code 1

这真的难倒我,因为这里的以下帖子特别指出这是您在条件 if 语句中使用正则表达式的方式:

Python: How to use RegEx in an if statement?

Regular Expression in conditional statement using Python 3

如果有人能指出我正在犯的一个简单错误,或者让与我处于类似情况的其他人知道如何在 python 3 中的条件 if 语句中正确使用正则表达式,我们将不胜感激!

【问题讨论】:

  • &amp; 应该是and
  • tl;dr - 但是关于测试字符串是否以ampm 结尾的条件,不要使用re。使用str.endswith('am')str.endswith('pm')。例如。 In: '8:00 pm'.endswith('pm') --&gt; Out: TrueIn: '8:00 pm'.endswith('am') --&gt; Out: False。当然,字符串变量而不是常量也是如此。
  • @JETM 哇,现在我觉得自己很蠢,不敢相信我没有查到。
  • 还有@SpghttCd str.endswith() 是否适用于不匹配的情况?

标签: python regex python-3.x


【解决方案1】:

re.search 返回匹配对象或无。首先,调用 re.search 并将其值存储在一个变量中,然后测试它是否为 None。在尝试从中提取值之前,请确保测试它是否不是 None。

另外,您不需要使用is not None 来检查某项是否等于无,只需将其作为布尔值进行测试。

最后,您似乎想从正则表达式中提取数据。如果你想这样做,你可以在正则表达式上调用group(0) 来获取匹配的内容(实际上是第一组,但你在正则表达式页面上阅读了更多关于这个的内容,这应该适合你的目的)。然后将结果转换为您需要的任何内容。例如,您可以找到并提取字符串中的第一个数字,并测试它是否大于某个值,如下所示:

import re

my_str = input()
match = re.search(r'\d+', my_str)

if match and int(match.group(0)) > 10:
     print('The input was greater than 10.')

希望这会有所帮助。如果您想了解更多关于正则表达式的信息,请查看文档。 文档:https://docs.python.org/3/library/re.html

【讨论】:

    【解决方案2】:

    请注意,我知道我的回答不是对您问题的回答 - 但是,我觉得告诉您以下内容仍然很重要。

    Regex 是一个非常强大的工具,它有它的目标应用程序或要解决的问题。但 IMO,你的不是正则表达式主题。

    有一个python库可以处理日期和时间。请考虑使用这样的方法:

    import datetime as DT
    
    start_time = input("Please enter the time you started working(ex -- 8:00am): \n")
    incorr_ans = True
    while incorr_ans:
        try:
            s_t = DT.datetime.strptime(start_time, '%I:%M%p')
            incorr_ans = False
        except:
            start_time = input("Please enter the time you started working(ex -- 8:00am): \n")
    
    end_time = input("Please enter the time you stopped working(ex -- 8:00am): \n")
    incorr_ans = True
    while incorr_ans:
        try:
            e_t = DT.datetime.strptime(end_time, '%I:%M%p')
            incorr_ans = False
        except:
            end_time = input("Please enter the time you stopped working(ex -- 8:00am): \n")
    
    print(s_t, e_t)
    print(e_t - s_t)
    

    请注意,程序的主要部分是由于用户输入的双重错误捕获。但我仍然认为这是一种非常方便的方式。并且:您的复杂计算在这里只是一个简单的减法...
    所以从用户的角度来看,这将导致一个程序,如:

    Please enter the time you started working(ex -- 8:00am): 
    8:34am
    
    Please enter the time you stopped working(ex -- 8:00am): 
    3:07pm
    1900-01-01 08:34:00 1900-01-01 15:07:00
    6:33:00
    

    只要看一遍,也许你会喜欢它并自己朝这个方向努力。 而且,如果您真的必须测试 re,因为它非常有趣 - 会有其他问题......

    【讨论】:

    • 谢谢,我最初正在考虑使用这个库,但从我所做的研究来看,我无法判断我是否可以使用它来保持我输入的时间,因此决定使用正则表达式。我之前在我的一个课程中学习过正则表达式,并想在这种情况下尝试一下。我想我会坚持使用正则表达式,因为这样可以更容易地以我可以复制到我的工作时间表中的格式得到我的答案,哈哈。不过,我一定会在未来的项目中尝试这个库,再次感谢您!
    • ;-)...“lol”正是对这个原因的正确评论...你在说什么格式?
    猜你喜欢
    • 2015-12-24
    • 2018-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-21
    • 2022-10-24
    • 1970-01-01
    相关资源
    最近更新 更多