试图建立学校虚拟助手

时间:2020-07-02 22:54:14

标签: python

嘿,所以我正在尝试构建学校虚拟助手,因此我目前正在研究所有与虚拟助手交互时如何要求日期的边缘案例。我个人认为可能已经捕获了大多数情况,看来情况并非如此,请您在以下代码上为我提供帮助。

以下代码

def get_date(text):

    text = text.lower()
    today = datetime.date.today()

    if text.count('today') > 0:
        return today

    day = -1
    day_of_week = -1
    month = -1
    year = today.year

    for word in text.split():
        if word in MONTHS:
            month = MONTHS.index(word) + 1

        elif word in DAYS:
            day_of_week = DAYS.index(word)

        elif word.isdigit():
            day = int(word)

        else:
            for ext in DAY_EXTENTIONS:
                found = word.find(ext)
                if found > 0:  # removing the extention if found and taking in the number e.g 5th---> 5
                
                    try:
                        day = int(word[:found])

                    except:
                        pass

    if month < today.month and month != -1:
        year = year + 1

    if day < today.day and month == -1 and day != -1:
        month = month + 1

    if month == -1 and day == -1 and day_of_week != -1:
        current_day_of_week = today.weekday()
        difference = day_of_week - current_day_of_week

    if difference < 0:
        difference += 7
        if text.count('next') >=1:
            difference += 7

        return today + datetime.timedelta(difference)

    return datetime.date(month=month, day=day, year=year)

我尝试过的测试案例

1。通过的第一个测试案例:

do I have plans on the 4th of July(INPUT)
2020-07-04(OUPUT)

2。第二次测试失败:

do I have any plans next week 3rd(INPUT)
Traceback (most recent call last):(OUTPUT)
  File "schoolAssistant.py", line 152, in <module>
    print(get_date(text))
  File "schoolAssistant.py", line 147, in get_date
    return datetime.date(month=month, day=day, year=year)
ValueError: month must be in 1..12

3。失败的第三个测试案例:

do I have plans next week Tuesday(INPUT)
2020-07-14(OUTPUT)

4。第四次测试失败:

do I have plans next week Monday(INPUT)
Traceback (most recent call last):(OUTPUT)
  File "schoolAssistant.py", line 152, in <module>
    print(get_date(text))
  File "schoolAssistant.py", line 147, in get_date
    return datetime.date(month=month, day=day, year=year)
ValueError: month must be in 1..12

5。第五个测试案例失败:

what do I have on the 5th(INPUT)
Traceback (most recent call last):(OUTPUT)
  File "schoolAssistant.py", line 152, in <module>
    print(get_date(text))
  File "schoolAssistant.py", line 147, in get_date
    return datetime.date(month=month, day=day, year=year)
ValueError: month must be in 1..12

0 个答案:

没有答案