Python 类型错误:Can';t将重新编译(';[A-Z]+;';)(重新模式)转换为联合[str,tokenizers.Regex]
将正则表达式应用于HuggingFace库中的Python 类型错误:Can';t将重新编译(';[A-Z]+;';)(重新模式)转换为联合[str,tokenizers.Regex],python,python-3.x,pytorch,huggingface-tokenizers,Python,Python 3.x,Pytorch,Huggingface Tokenizers,将正则表达式应用于HuggingFace库中的Split()操作时遇到问题。为Split()请求以下输入 模式(str或Regex)–用于分割字符串的模式。通常是 string或Regex 在我的代码中,我应用了Split()操作,如下所示: tokenizer.pre_tokenizer = Split(pattern="[A-Z]+", behavior='isolated') 但它不起作用,因为[A-Z]+被解释为字符串而不是正则表达式。我使用了以下方法,但毫无用处:
Split()
操作时遇到问题。为Split()
请求以下输入
模式(str或Regex)–用于分割字符串的模式。通常是
string
或Regex
在我的代码中,我应用了Split()
操作,如下所示:
tokenizer.pre_tokenizer = Split(pattern="[A-Z]+", behavior='isolated')
但它不起作用,因为[A-Z]+
被解释为字符串而不是正则表达式。我使用了以下方法,但毫无用处:
pattern = re.compile("[A-Z]+")
tokenizer.pre_tokenizer = Split(pattern=pattern, behavior='isolated')
获取以下错误:
TypeError:无法将re.compile('[A-Z]+')(re.Pattern)转换为Union[str,tokenizers.Regex]
以下解决方案通过从tokenizers库导入
Regex
工作:
from tokenizers import Regex
tokenizer.pre_tokenizer = Split(pattern=Regex("[A-Z]+"),
behavior='isolated')
“[A-Z]+”
是字符串而不是正则表达式re.compile(…)
是一种re.Pattern
而不是tokenizers.Regex
。也许是从hugging face导入tokenizers.Regex。我不知道你从哪里发现了tokenizers.Regex
,因为它不在文档中,但它工作了。从错误本身TypeError
是变量的类型的错误。所以它告诉您它不匹配Union[str,tokenizers.Regex]
。这称为类型暗示,Union
表示或
。因此,它期望一个str
或tokenizers.Regex
。这就是我提出这个建议的原因。@thethiny的答案值得称赞