python - 防止 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 的令牌,但不知道如何避免特定的拆分技术。
解决方案
我建议使用自定义标记器,请参阅修改现有规则集:
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),
推荐阅读
- selenium - Proxy is ignored for localhost in docker selenium version: 3.141.59-zinc
- javascript - Save array from a JSON fetch
- async-await - How wait until complet http request in angular-7
- r - R remove column of df inside list of list
- android - Android Q 显示错误的渐变方向
- docker - Is it possible to use Traefik if you have a DNS provider not on their list?
- java - 如何将流收集到列表中?
- sparql - Retrieve wikidata related data entities from wikipedia
- javascript - 如何限制axios同时对同一个资源发出2个以上的请求
- selenium - 在 Selenium 测试中是否有一个 Chrome 标志来禁用渐进式网络应用程序 (PWA) 的通知?