Tech With Tim Logo
Go back

Date From Speech

In this tutorial we will start writing a function that can determine what a specific date from a string of text. We will use this to allow the user to ask the bot about its google calendar schedule on a certain day.

Defining Months and Days

Since the user will be asking things like: "What do I have on September 3rd", "Do I have any plans of Friday?" we need to define which words are days and months, we also need to define possible suffixes on numbers (like 2nd, or 4th). We will start by defining some lists with this information.

MONTHS = ["january", "february", "march", "april", "may", "june","july", "august", "september","october", "november", "december"]
DAYS = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]
DAY_EXTENTIONS = ["rd", "th", "st", "nd"]

Getting The Date From Text

Now we will create a function that can read a string of text and extract the date from it. This is fairly complex due to the amount of ways someone can describe a date. Below are some examples of things people may say: "What do I have on January Third" "What's my schedule like on Friday" "Do I have anything next Monday" "What does my day look like on the 5th" So you can see how many different ways someone could describe the date.

Here's the start of the function:

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:
                    try:
                        day = int(word[:found])
                    except:
                        pass

This will parse the text passed in and look for a month and/or a day. When we finish this function in the next tutorial we will include the code to handle days of the week (Wednesday, Friday etc.)

Design & Development by Ibezio Logo