首页 > 解决方案 > 防止 Spacy 分词器拆分特定字符

问题描述

当使用 spacy 标记一个句子时,我希望它不分裂成标记/

例子:

import en_core_web_lg
nlp = en_core_web_lg.load()
for i in nlp("Get 10ct/liter off when using our App"):
    print(i)

输出:

Get
10ct
/
liter
off
when
using
our
App

我希望它像Get , 10ct/liter, off, when ....

我能够找到如何添加更多方法来拆分为 spacy 的令牌,但不知道如何避免特定的拆分技术。

标签: pythonnlptokenizespacy

解决方案


我建议使用自定义标记器,请参阅修改现有规则集

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

nlp = spacy.load("en_core_web_trf")
text = "Get 10ct/liter off when using our App"
# Modify tokenizer infix patterns
infixes = (
    LIST_ELLIPSES
    + LIST_ICONS
    + [
        r"(?<=[0-9])[+\-\*^](?=[0-9-])",
        r"(?<=[{al}{q}])\.(?=[{au}{q}])".format(
            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),
        r"(?<=[{a}0-9])[:<>=](?=[{a}])".format(a=ALPHA),
    ]
)

infix_re = compile_infix_regex(infixes)
nlp.tokenizer.infix_finditer = infix_re.finditer
doc = nlp(text)
print([t.text for t in doc])
## =>  ['Get', '10ct/liter', 'off', 'when', 'using', 'our', 'App']

注意注释#r"(?<=[{a}0-9])[:<>=/](?=[{a}])".format(a=ALPHA),行,我只是/[:<>=/]字符类中取出字符。/该规则在字母/数字和字母之间拆分。

如果仍需要拆分'12/ct'为三个标记,则需要在该行下方添加另一r"(?<=[{a}0-9])[:<>=](?=[{a}])".format(a=ALPHA)行:

r"(?<=[0-9])/(?=[{a}])".format(a=ALPHA),

推荐阅读