How can I find as many date patterns as possible from a text file by python? The date pattern is defined as:
dd mmm yyyy
^ ^
| |
+---+--- spaces
where:
Thanks!
Here's a way to find all dates matching your pattern
re.findall(r'\d\d\s(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s\d{4}', text)
But after WilhelmTell's comment on your question, I'm also wondering whether this it what you were really asking for...
Use the calendar module to give you a little global awareness:
date_expr = r"\d{2} (?:%s) \d{4}" % '|'.join(calendar.month_abbr[1:])
print date_expr
print re.findall(date_expr, source_text)
For me, this creates a date_expr like:
"\d{2} (:?Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) \d{4}"
But if I change my locale using the locale module:
locale.setlocale(0, "fr")
I now search for months in French:
"\d{2} (?:janv.|févr.|mars|avr.|mai|juin|juil.|août|sept.|oct.|nov.|déc.) \d{4}"
Hmm, this is the first time I ever tried French month abbreviations, I may need to do some cleanup:
date_expr = r"\d{2} (?:%s) \d{4}" % '|'.join(
m.title().rstrip('.') for m in calendar.month_abbr[1:])
Now I get:
"\d{2} (?:Janv|Févr|Mars|Avr|Mai|Juin|Juil|Août|Sept|Oct|Nov|Déc) \d{4}"
And now my script will run for my Gallic friends as well, with really very little trouble.
(You may wonder why I had to slice the month_abbr list from [1:] - this list begins with an empty string in position 0, so that if you use find() to look up a particular month abbreviation, you will get back a number from 1-12, instead of from 0-11.)
-- Paul
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With