如何将自定义符号添加到Spacy的标点符号功能?
问题描述
是否有添加默认标点规则中不包括的自定义标点符号的选项?(https://github.com/explosion/spaCy/blob/develop/spacy/lang/de/punctuation.py)
我正在使用Spacy的Matcher类(https://spacy.io/usage/rule-based-matching)和属性"is_PUNCT"从我的文本中删除标点符号。from spacy.matcher import Matcher
# instantiate Matcher
matcher = Matcher(nlp.vocab)
# define pattern
pattern = [{"IS_PUNCT": False}]
# add pattern to matcher
matcher.add("Cleaning", None, pattern)
我想要自定义标点符号规则,以便能够使用Matcher从我的文本中删除"|"。
解决方案
您可以通过将lex_attr_getters[IS_PUNCT]
函数替换为包含描述其他字符的符号列表的自定义函数来完成此操作。
import spacy
from spacy.symbols import IS_PUNCT
from spacy.lang.en import EnglishDefaults
def is_punct_custom(text):
extra_punct = ["|"]
if text in extra_punct:
return True
return is_punct_original(text)
# Keep a reference to the original is_punct function
is_punct_original = EnglishDefaults.lex_attr_getters[IS_PUNCT]
# Assign a new function for IS_PUNCT
EnglishDefaults.lex_attr_getters[IS_PUNCT] = is_punct_custom
相关文章