NLP: Find and normalize dates

Pull dates written in different styles out of text and write them all the same way.

What to build

A program that finds dates in three formats and prints them as YYYY-MM-DD.

Requirements

  • Recognize YYYY-MM-DD, D/M/YYYY (day first; day and month have one or two digits) and Month D, YYYY with a full English month name in any letter case, such as april 30, 2024.
  • In the third format, a word that is not a month name is ignored (only 12, 2024 is not a date). Do not check whether dates are valid.
  • Print dates found: N, then each date as YYYY-MM-DD, in the order they appear.

Input

Line 1: n. Then n lines of text.

Output

One count line, then one line per date.

Constraints

n ≤ 100; each line has at most 500 characters.

Example

Input:

2
Due 2024-03-15, moved to 1/4/2024.
Final: April 30, 2024.

Output:

dates found: 3
2024-03-15
2024-04-01
2024-04-30

Why it works

A single pattern with alternatives scans the text once from left to right, so the dates come out in reading order, and the groups give each part of the date to convert.

Examples

Example 1 · Input
2
Due 2024-03-15, moved to 1/4/2024.
Final: April 30, 2024.
Expected output
dates found: 3
2024-03-15
2024-04-01
2024-04-30
Example 2 · Input
1
No dates here, only 12, 2024 things.
Expected output
dates found: 0

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

One pattern with three alternatives keeps the dates in text order: `(\d{4})-(\d{2})-(\d{2})|(\d{1,2})/(\d{1,2})/(\d{4})|([A-Za-z]+) (\d{1,2}), (\d{4})`.

Hint 2

`m.groups()` gives nine values; the ones of the alternative that did not match are `None`.

Solution

Show one correct solution (try it yourself first)
import re

MONTHS = ["january", "february", "march", "april", "may", "june", "july",
          "august", "september", "october", "november", "december"]
PATTERN = re.compile(
    r"(\d{4})-(\d{2})-(\d{2})"
    r"|(\d{1,2})/(\d{1,2})/(\d{4})"
    r"|([A-Za-z]+) (\d{1,2}), (\d{4})"
)
found = []
for _ in range(int(input())):
    for m in PATTERN.finditer(input()):
        g = m.groups()
        if g[0]:
            y, mo, d = int(g[0]), int(g[1]), int(g[2])
        elif g[3]:
            y, mo, d = int(g[5]), int(g[4]), int(g[3])
        elif g[6].lower() in MONTHS:
            y, mo, d = int(g[8]), MONTHS.index(g[6].lower()) + 1, int(g[7])
        else:
            continue
        found.append(f"{y:04d}-{mo:02d}-{d:02d}")
print("dates found:", len(found))
for date in found:
    print(date)

Lesson: Regular expressions for text →