首页 > 解决方案 > 当日期可以输入为 04-14-2021 和 04-2022 和 4-2021 时,在 spacy 中指定正则表达式

问题描述

当日期可以输入为 04-14-2021 和 04-2022 和 4-2021 时,如何在 spacy 中指定正则表达式。

对于连字符,我正在使用这个正则表达式:

import spacy
from spacy.tokens.doc import Doc
from spacy.matcher import Matcher
nlp = spacy.load('en_core_web_sm')

matcher = Matcher(nlp.vocab)  
doc: Doc = nlp("4-15-2024 02-26 02 6-2021 05-2021")

pattern_9 = [{'TEXT':{'REGEX':r'^\d{1,2}$'}}, {'TEXT':{'REGEX':r'^-$'}}, {'TEXT':{'REGEX':r'^\d{2,4}$'}}] #e.g. Jun-2021

matcher.add('DATE_PATTERN_9', [pattern_9])

matches = matcher(doc)
print(f"matches = {matches}")

for match_id, start, end in matches:
    string_id = nlp.vocab.strings[match_id]  # Get string representation
    span = doc[start:end]  # The matched span
    print( span.text)
    

文档:

Doc = nlp("4-15-2024 02-26 02 6-2021 05-2021")

它分成4-15-2024&4-1515-2024我只想要mm-yymm-yyyy作为输出。

现在,我得到低于上述模式的输出:

4-15
15-2024
02-26
6-2021
05-2021

标签: pythonregexdatespacy

解决方案


推荐阅读