spaCy的正则表达式不同于Python的正则表达式

时间:2019-08-30 13:19:46

标签: python regex spacy

我有以下文字

text = 'Monday to Friday 12 midnight to 5am 30% . Midnight Friday to 6am Saturday 30% . 9pm Saturday to Midnight Saturday 25% . Midnight Saturday to 6am Sunday 100% . 6am Sunday to 9pm Sunday 50%'

当我使用 normal 正则表达式时,获得了以下内容

import re
regex = '\d{1}[a|p]m'
re.findall(regex, text)

# Returned:
['5am', '6am', '9pm', '6am', '6am', '6pm']

但是,当我在spaCy中使用相同的regex时,我什么也没回来

from spacy.matcher import Matcher
nlp = spacy.load('en_core_web_lg')

matcher = Matcher(nlp.vocab)
pattern = [{'TEXT': {'REGEX': '\d{1}[a|p]m'}}]
matcher.add('TIME', None, pattern)

doc = nlp(text)
matches = matcher(doc)

for match_id, start, end in matches:
    matched_span = doc[start:end]
    print(matched_span.sent.text)

这是否意味着我们不能在spaCy中使用 normal 正则表达式?如果是这样,您知道我在哪里可以学习spaCy的 special regex语法?谢谢。

1 个答案:

答案 0 :(得分:3)

您需要记住,数字将与此处的字母分开,请参见测试:

doc = nlp("1pm")
print([token.text for token in doc]) # => ['1', 'pm']

根据Spacy docs

  

如果spaCy的令牌化与模式中定义的令牌不匹配,则该模式将不会产生任何结果。

您需要使用基于规则的匹配来定义自己的实体:

pattern = [{'LIKE_NUM': True}, {'LOWER': {'REGEX' : '^[ap]m$'}}]

然后将其添加到匹配器:

matcher.add('TIME', None, pattern)

并获取匹配项:

for match_id, start, end in matches:
    span = doc[start:end]  # The matched span
    print(span.text)

完整演示:

import spacy
from spacy.matcher import Matcher

nlp = spacy.load("en_core_web_sm")

text = 'Monday to Friday 12 midnight to 5am 30% . Midnight Friday to 6am Saturday 30% . 9pm Saturday to Midnight Saturday 25% . Midnight Saturday to 6am Sunday 100% . 6am Sunday to 9pm Sunday 50%'
doc = nlp(text)

matcher = Matcher(nlp.vocab)
pattern = [{'LIKE_NUM': True}, {'LOWER': {'REGEX' : '^[ap]m$'}}]
matcher.add('TIME', None, pattern)

matches = matcher(doc)
print([doc[start:end] for match_id, start, end in matches])
#=> [5am, 6am, 9pm, 6am, 6am, 9pm]