Search code examples
pythonpython-re

Regular Expression in Python using months abbreviation


I have several thousand lines like:

"The sequence 1,-2,-1,2,1,-2,-1,2,... with g.f. (1-2x)/(1+x^2) has a(n) = cos(Pi*n/2)-2*sin(Pi*n/2). - Paul Barry, Oct 18 2004"

and I need to find the position, if any, of the date that show up as abbreviations like 'Aug 03'. For this reason I wrote a function _find_all_positions that takes as input a string and a date specifier from 'Jan 01' to 'Dec 31' in a for loop.

def _add_zero(value: int) -> str:
   """add zero to number with digits < 2"""
   value_str = str(value)
   digits = len(value_str)
   if digits < 2:
       value_str = '0' + value_str
   return value_str
    
def get_date() -> list:
    """Get dates for author(s) search, from ' Jan 01' to ' Dec 31' """
    dates = list()
    months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
    for month in months:
        for day in range(1, 32):
            dates.append(' ' + month + ' ' + ParserUtilities._add_zero(day))
    return dates

def _find_all_positions(string: str, sub: str):
    """Find all occurrences of a substring in a string"""
    start = 0
    while True:
        start = string.find(sub, start)
        if start == -1:
            return
        yield start
        start += len(sub)  # use start += 1 to find overlapping matches

The task is quite slow and I would like to know if with Regular Expression it would be possible to speed up the search


Solution

  • You can put all months in one regular expression:

    def find_all_positions(text):
        for match in re.finditer('(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ([012][0-9]|30|31)', text):
            yield math.start()