Search code examples
pythondictionarydate-conversion

Date conversion from numbers to words in Python


I wrote a program in python(I'm a beginner still) that converts a date from numbers to words using dictionaries. The program is like this:

dictionary_1 = { 1:'first', 2:'second'...}
dictionary_2 = { 1:'January', 2:'February',...}

and three other more for tens, hundreds, thousands;

  • 2 functions, one for years <1000, the other for years >1000;
  • an algorithm that verifies if it's a valid date.

In main I have:

a_random_date = raw_input("Enter a date: ") 

(I've chosen raw_input for special chars. between numbers such as: 21/11/2014 or 21-11-2014 or 21.11.2014, only these three) and after verifying if it's a valid date I do not know nor did I find how to call upon the dictionaries to convert the date into words, when I run the program I want at the output for example if I typed 1/1/2015: first/January/two thousand fifteen. And I would like to apply the program to a text document to seek the dates and convert them from numbers to words if it is possible. Thank you!


Solution

  • You can split that date in list and then check if there is that date in dictionary like this:

    import re
    
    dictionary_1 = { 1:'first', 2:'second'}
    dictionary_2 = { 1:'January', 2:'February'}
    dictionary_3 = { 1996:'asd', 1995:'asd1'}
    
    input1 = raw_input("Enter date:")
    lista = re.split(r'[.\/-]', input1)
    print "lista: ", lista
    day = lista[0]
    month = lista[1]
    year = lista[2]
    everything_ok = False
    if dictionary_1.get(int(day)) != None:
       day_print = dictionary_1.get(int(day))
       everything_ok = True
    else:
       print "There is no such day"
    if dictionary_2.get(int(month)) != None:
       month_print = dictionary_2.get(int(month))
       everything_ok = True
    else:
       print "There is no such month"
       everything_ok = False
    if dictionary_3.get(int(year)) != None:
       year_print = dictionary_3.get(int(year))
       everything_ok = True
    else:
       print "There is no such year"
       everything_ok = False
    if everything_ok == True:
       print "Date: ", day_print, "/", month_print, "/", year_print #or whatever format
    else:
       pass
    

    This is the output:

    Enter date:1/2/1996
    Date:  first / February / asd
    

    I hope this helps you.