因题外话编辑
我想在 SpaCy 中使用正则表达式通过以下代码查找(应计或应计或年度或年度)休假的任意组合:
from spacy.matcher import Matcher
nlp = spacy.load('en_core_web_sm')
matcher = Matcher(nlp.vocab)
# Add the pattern to the matcher
matcher.add('LEAVE', None,
[{'TEXT': {"REGEX": "(Accrued|accrued|Annual|annual)"}},
{'LOWER': 'leave'}])
# Call the matcher on the doc
doc= nlp('Annual leave shall be paid at the time . An employee is to receive their annual leave payment in the normal pay cycle. Where an employee has accrued annual leave in')
matches = matcher(doc)
# Iterate over the matches
for match_id, start, end in matches:
# Get the matched span
matched_span = doc[start:end]
print('- ', matched_span.sent.text)
# returned:
- Annual leave shall be paid at the time .
- An employee is to receive their annual leave payment in the normal pay cycle.
- Where an employee has accrued annual leave in
但是,我认为我的正则表达式不够抽象/泛化,无法应用于其他情况,非常感谢您就如何使用 spaCy 改进我的正则表达式提出建议。
请您参考如下方法:
你的代码没问题,你只是在 ananual 中有一个拼写错误,然后你的代码将产生所有 3 个句子。
但是,您不需要重复大小写不同的单词。使用 Python re 正则表达式,您可以传递 (?i) inline modifier到模式开始,它将不区分大小写。
你可以使用
"(?i)accrued|annual"
或者,为了匹配整个单词,添加单词边界 \b:
r"(?i)\b(?:accrued|annual)\b"
请注意开头 " 之前的 r 前缀使字符串文字成为 raw,您不必转义 \ 在其中。r"\b" = "\\b"。
(?:...) non-capturing group是否可以确保 \b 字边界应用于组内的所有替代项。例如,\baccrued|annual\b 将匹配 accruednesssss 或 biannual(它将匹配以 accrued 或以 annual 结尾的那些)。
