【发布时间】:2020-05-16 12:29:51
【问题描述】:
感谢收看。我正在使用 spaCy 对一段文本执行命名实体识别,但我遇到了一个似乎无法克服的特殊问题。这是一个示例代码:
from spacy.tokenizer import Tokenizer
nlp = spacy.load("en_core_web_sm")
doc = nlp('The Indo-European Caucus won the all-male election 58-32.')
这会导致以下结果:
['The', 'Indo', '-', 'European', 'Caucus', 'won', 'the', 'all', '-', 'male', 'election', ',', '58', '-', '32', '.']
我的问题是我需要那些包含连字符的单词和数字作为单个标记。我按照this answer 给出的示例使用以下代码:
inf = list(nlp.Defaults.infixes)
inf = [x for x in inf if '-|–|—|--|---|——|~' not in x] # remove the hyphen-between-letters pattern from infix patterns
infix_re = compile_infix_regex(tuple(inf))
def custom_tokenizer(nlp):
return Tokenizer(nlp.vocab, prefix_search=nlp.tokenizer.prefix_search,
suffix_search=nlp.tokenizer.suffix_search,
infix_finditer=infix_re.finditer,
token_match=nlp.tokenizer.token_match,
rules=nlp.Defaults.tokenizer_exceptions)
nlp.tokenizer = custom_tokenizer(nlp)
这有助于字母字符,我得到了这个:
['The', 'Indo-European', 'Caucus', 'won', 'the', 'all-male', 'election', ',', '58', '-', '32', '.']
这好多了,但'58-32' 仍然被拆分为单独的标记。我试了this answer,得到了相反的效果:
['The', 'Indo', '-', 'European', 'Caucus', 'won', 'the', 'all', '-', 'male', 'election', ',' '58-32', '.']
如何更改分词器以在两种情况下都给我正确的结果?
【问题讨论】:
-
您删除了对词内连字符(即字母之间的连字符)的支持,但不支持数字之间的连字符。
-
是的,我认为是这样,但我没有 Python 技能来结合这些要求。我正在下面尝试您的解决方案;我应该在大约 15 分钟内知道它是否有效。我很高兴你回复了;您对其他 spaCy 问题的解决方案很有帮助!
标签: python regex tokenize spacy