【问题标题】:Spacy - modify tokenizer for numeric patternsSpacy - 修改数字模式的标记器
【发布时间】:2020-06-29 15:31:24
【问题描述】:

我已经看到了一些创建自定义标记器的方法,但我有点困惑。我正在做的是使用短语匹配器来匹配模式。但是,它会匹配一个 4 位数字模式,例如 1234,在 111-111-1234,因为它在破折号上分裂。

我想要做的就是修改当前的分词器(来自nlp = English())并添加一条规则,它不应该在某些字符上拆分,而只能用于数字模式。

【问题讨论】:

  • 您能否添加一些输入和预期输出作为示例?
  • 例如,111-111-1234 应该是 111-111-1234 -- 它不应该在 - 上拆分。另外,如果单词从小写变为大写,想添加拆分:abcDE 将变为 ['abc','DE']

标签: python tokenize spacy


【解决方案1】:

为此,您需要用您自己的覆盖 spaCy 的默认 infix 标记化方案。您可以通过修改 here 找到的 spaCy 使用的中缀标记化方案来做到这一点。

import spacy
from spacy.lang.char_classes import ALPHA, ALPHA_LOWER, ALPHA_UPPER, HYPHENS
from spacy.lang.char_classes import CONCAT_QUOTES, LIST_ELLIPSES, LIST_ICONS
from spacy.util import compile_infix_regex

# default tokenizer
nlp = spacy.load("en_core_web_sm")
doc = nlp("111-222-1234 for abcDE")
print([t.text for t in doc])

# modify tokenizer infix patterns
infixes = (
        LIST_ELLIPSES
        + LIST_ICONS
        + [
            r"(?<=[0-9])[+\*^](?=[0-9-])", # Remove the hyphen
            r"(?<=[{al}{q}])\.?(?=[{au}{q}])".format( # Make the dot optional
                al=ALPHA_LOWER, au=ALPHA_UPPER, q=CONCAT_QUOTES
            )
            ,
            r"(?<=[{a}]),(?=[{a}])".format(a=ALPHA),
            r"(?<=[{a}])(?:{h})(?=[{a}])".format(a=ALPHA, h=HYPHENS),
            r"(?<=[{a}0-9])[:<>=/](?=[{a}])".format(a=ALPHA),
        ]
)

infix_re = compile_infix_regex(infixes)
nlp.tokenizer.infix_finditer = infix_re.finditer
doc = nlp("111-222-1234 for abcDE")
print([t.text for t in doc])

输出

With default tokenizer:
['111', '-', '222', '-', '1234', 'for', 'abcDE']

With custom tokenizer:
['111-222-1234', 'for', 'abc', 'DE']

【讨论】:

  • 谢谢!你知道这是否可以编辑:我不想将RE: 拆分为['RE',':']。换句话说,如果有一个'RE'后跟一个冒号,不要拆分。可以通过修改这些中缀之一在此处添加吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-05
相关资源
最近更新 更多