Go back
Date From Speech P2
Subscribe to Tech with Tim
YouTube
In this tutorial we will finish our get_date() function and test it out!
PLEASE USE THE CODE BELOW, IT FIXES SOME ERRORS FROM THE VIDEO ABOVE
Finishing get_date()
Now that we have extracted the information from the text it's time to process it. There are a few scenarios we need to consider: 1. We have a day but no month 2. We have only a day of the week 3. The date mentioned is before the current date 4. We don't find a date
There are a few other ones as well but these are our main concern.
And here is the rest of the function to handle the above situations.
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 # THE NEW PART STARTS HERE if month < today.month and month != -1: # if the month mentioned is before the current month set the year to the next year = year+1 # This is slighlty different from the video but the correct version if month == -1 and day != -1: # if we didn't find a month, but we have a day if day < today.day: month = today.month + 1 else: month = today.month # if we only found a dta of the week if month == -1 and day == -1 and day_of_week != -1: current_day_of_week = today.weekday() dif = day_of_week - current_day_of_week if dif < 0: dif += 7 if text.count("next") >= 1: dif += 7 return today + datetime.timedelta(dif) if day != -1: # FIXED FROM VIDEO return datetime.date(month=month, day=day, year=year)
Testing and Using get_date()
Now that we have created this function it's time to use it and see if it works!
Let's add this to our mainline and start saying some dates to the computer!
text = get_audio() print(get_date(text))