gpt4 book ai didi

python - 在 Spacy 中向标记器添加一些自定义单词

转载 作者:行者123 更新时间:2023-12-03 08:51:24 35 4
gpt4 key购买 nike

我有一个句子,希望看到如下预期的标记。

Sentence: "[x] works for [y] in [z]."
Tokens: ["[", "x", "]", "works", "for", "[", "y", "]", "in", "[", "z", "]", "."]
Expected: ["[x]", "works", "for", "[y]", "in", "[z]", "."]

如何通过自定义分词器函数来做到这一点?

最佳答案

您可以从标记器前缀和后缀中删除 [],以便括号不会与相邻标记分开:

import spacy
nlp = spacy.load('en_core_web_sm')

prefixes = list(nlp.Defaults.prefixes)
prefixes.remove('\\[')
prefix_regex = spacy.util.compile_prefix_regex(prefixes)
nlp.tokenizer.prefix_search = prefix_regex.search

suffixes = list(nlp.Defaults.suffixes)
suffixes.remove('\\]')
suffix_regex = spacy.util.compile_suffix_regex(suffixes)
nlp.tokenizer.suffix_search = suffix_regex.search

doc = nlp("[x] works for [y] in [z].")
print([t.text for t in doc])
# ['[x]', 'works', 'for', '[y]', 'in', '[z]', '.']

相关文档在这里:

https://spacy.io/usage/linguistic-features#native-tokenizer-additions

关于python - 在 Spacy 中向标记器添加一些自定义单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58686259/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com