I am new to text mining and I need to extract the dates from a *.txt file and sort them. The dates are in between the sentences ( each line) and their format can potentially be as follows:
04/20/2009; 04/20/09; 4/20/09; 4/3/09
Mar-20-2009; Mar 20, 2009; March 20, 2009; Mar. 20, 2009; Mar 20 2009;
20 Mar 2009; 20 March 2009; 20 Mar. 2009; 20 March, 2009
Mar 20th, 2009; Mar 21st, 2009; Mar 22nd, 2009
Feb 2009; Sep 2009; Oct 2010
6/2008; 12/2009
2009; 2010
If the day is missing consider the 1st and if the month is missing consider January.
My idea is to extract all dates and convert that into mm/dd/yyyy format. However I am a bit doubtful on how to find and replace paterns. This is what i have done :
import pandas as pd
doc = []
with open('dates.txt') as file:
for line in file:
doc.append(line)
df = pd.Series(doc)
df2 = pd.DataFrame(df,columns=['text'])
def myfunc(x):
if len(x)==4:
x = '01/01/'+x
else:
if not re.search('/',x):
example = re.sub('[-]','/',x)
terms = re.split('/',x)
if (len(terms)==2):
if len(terms[-1])==2:
x = '01/'+terms[0]+'/19'+terms[-1]
else:
x = '01/'+terms[0]+'/'+terms[-1]
elif len(terms[-1])==2:
x = terms[0].zfill(2)+'/'+terms[1].zfill(2)+'/19'+terms[-1]
return x
df2['text'] = df2.text.str.replace(r'(((?:\d+[/-])?\d+[/-]\d+)|\d{4})', lambda x: myfunc(x.groups('Date')[0]))
I have done it only for the numerical dates format. But I am a bit confused how to do it with the alfanumerical dates.
I know is a rough code but this is just what I got.