首页 > 解决方案 > 使用Regex python提取月份之前的年份

问题描述

我有数千个数据集,我有兴趣从中提取一个月之前的年份。例如:

在数据集 1:1980 年 9 月

在数据集 2 中:1978 年 10 月

我使用https://regex101.com/编写的正则表达式:

^(?<month>)\w+(\1)\s[0-9]{4}$|(^(?<fmonth>)\w+,\s[0-9]{4}$)

它确实使用链接完成了这项工作。但是,当我尝试在我的 python 代码中使用它时,我收到以下错误:

  File "<ipython-input-216-a995358d0957>", line 1, in <module>
    runfile('C:/Users/Muntabir/nltk_data/corpora/cookbook/clean_data/text-classification_year(clean).py', wdir='C:/Users/Muntabir/nltk_data/corpora/cookbook/clean_data')
  File "C:\Users\Muntabir\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 705, in runfile
    execfile(filename, namespace)
  File "C:\Users\Muntabir\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)
  File "C:/Users/Muntabir/nltk_data/corpora/cookbook/clean_data/text-classification_year(clean).py", line 76, in <module>
    year_data = re.findall('^(?<month>)\w+(\1)\s[0-9]{4}$|(^(?<fmonth>)\w+,\s[0-9]{4}$)', tokenized_string)
  File "C:\Users\Muntabir\Anaconda3\lib\re.py", line 222, in findall
    return _compile(pattern, flags).findall(string)
  File "C:\Users\Muntabir\Anaconda3\lib\re.py", line 301, in _compile
    p = sre_compile.compile(pattern, flags)
  File "C:\Users\Muntabir\Anaconda3\lib\sre_compile.py", line 562, in compile
    p = sre_parse.parse(p, flags)
  File "C:\Users\Muntabir\Anaconda3\lib\sre_parse.py", line 855, in parse
    p = _parse_sub(source, pattern, flags & SRE_FLAG_VERBOSE, 0)
  File "C:\Users\Muntabir\Anaconda3\lib\sre_parse.py", line 416, in _parse_sub
    not nested and not items))
  File "C:\Users\Muntabir\Anaconda3\lib\sre_parse.py", line 691, in _parse
    len(char) + 2)
error: unknown extension ?<m

我不确定为什么会导致此错误。谁能给我一个可能的解决方案的解释?您的帮助将不胜感激。

谢谢

标签: pythonregex

解决方案


我非常感谢您的所有贡献。但是@Joan Lara Ganau 的解决方案为我提供了正则表达式的指导。@Joan,如果任何年份之前有月份和日期,您的正则表达式将匹配。此外,它不搜索逗号和空格。正如我所提到的,我有数千个数据集,我希望从中提取一个月之前的年份。我正在寻找以下格式:

a.) 月年 b.) 月、年

无论如何,经过多次实验,我找到了解决问题的方法。解决方案是:

year_result = re.compile(
                    r"(Jan(uary)?|Feb(ruary)?|Mar(ch)?|Apr(il)?|May|Jun(e)?|"
                    "Jul(y)?|Aug(ust)?|Sep(tember)?|Oct(ober)?|Nov(ember)?|"
                    "Dec(ember)?)(,?)(\s\d{4})")

此外,如果模式不匹配,match() 方法也将返回None 。在这种情况下,使用 group() 方法将引发 AttributeError。错误类似于无类型对象没有匹配的组()。所以,我用以下方式修复它:

def matched(document):                   
         year = year_result.match(document)
         year = year_result.search(document)
         if year is None:
               return '0'
         return year.group(14)

现在,您可以将要提取年份的文本文档传递给上述函数。

谢谢


推荐阅读