python - 使用带有特殊字符的 Spacy 分词器的问题
问题描述
我是 Spacy 的新手,我正在尝试在文本中找到一些模式,但由于标记化工作的形式,我遇到了麻烦。例如,我创建了以下模式,尝试使用 Matcher 查找像“0,42%”这样的百分比元素(这不是我想要的,但我现在只是在练习):
nlp = spacy.load("pt_core_news_sm")
matcher = Matcher(nlp.vocab)
text = 'total: 1,80%:(comex 1,30% + deriv 0,50%/ativo: 1,17% '
pattern_test = [{"TEXT": {"REGEX": "[0-9]+[,.]+[0-9]+[%]"}}]
text_ = nlp(text)
matcher.add("pattern test", [pattern_test] )
result = matcher(text_)
for id_, beg, end in result:
print(id_)
print(text_[beg:end])
问题是它返回的结果如下所示,因为标记化认为这只是一个标记:
9844711491635719110
1,80%:(comex
9844711491635719110
0,50%/ativo
我尝试在字符串上使用 Python 的 .replace() 方法在对其进行标记之前替换空格的特殊字符,但是现在当我打印标记化结果时,它会像这样分隔所有内容:
text_adjustment = text.replace(":", " ").replace("(", " ").replace(")", " ").replace("/", " ").replace(";", " ").replace("-", " ").replace("+", " ")
print([token for token in text_adjustment])
['t', 'o', 't', 'a', 'l', ' ', ' ', '1', ',', '8', '0', '%', ' ', ' ', 'c', 'o', 'm', 'e', 'x', ' ', '1', ',', '3', '0', '%', ' ', ' ', ' ', 'd', 'e', 'r', 'i', 'v', ' ', '0', ',', '5', '0', '%', ' ', 'a', 't', 'i', 'v', 'o', ' ', ' ', '1', ',', '1', '7', '%', ' ']
我希望标记化结果是这样的:
['total', '1,80%', 'comex', '1,30%', 'deriv', '0,50%', 'ativo', '1,17%']
有没有更好的方法来做到这一点?我正在使用“pt_core_news_sm”模型,但如果我愿意,我可以更改语言。
提前致谢 :)
解决方案
我建议使用
import re
#...
text = re.sub(r'(\S)([/:()])', r'\1 \2', text)
pattern_test = [{"TEXT": {"REGEX": r"^\d+[,.]\d+$"}}, {"ORTH": "%"}]
在这里,(\S)([/:()])
正则表达式用于匹配任何非空白(将其捕获到第 1 组),然后匹配 a /
, :
, (
or )
(将其捕获到第 2 组),然后re.sub
在这两个组之间插入一个空格。
正^\d+[,.]\d+$
则表达式匹配包含浮点值的完整标记文本,并且%
是下一个标记文本(因为数字并被%
模型拆分为单独的标记)。
完整的 Python 代码片段:
import spacy, re
from spacy.matcher import Matcher
#nlp = spacy.load("pt_core_news_sm")
nlp = spacy.load("en_core_web_trf")
matcher = Matcher(nlp.vocab)
text = 'total: 1,80%:(comex 1,30% + deriv 0,50%/ativo: 1,17% '
text = re.sub(r'(\S)([/:()])', r'\1 \2', text)
pattern_test = [{"TEXT": {"REGEX": "\d+[,.]\d+"}}, {"ORTH": "%"}]
text_ = nlp(text)
matcher.add("pattern test", [pattern_test] )
result = matcher(text_)
for id_, beg, end in result:
print(id_)
print(text_[beg:end])
输出:
9844711491635719110
1,80%
9844711491635719110
1,30%
9844711491635719110
0,50%
9844711491635719110
1,17%
推荐阅读
- android - 当提供商是电子邮件/密码时,如何仅发送密码重置电子邮件
- javascript - javascript - 像在 php 中一样获取日期格式?
- c# - 有没有办法将 WriteLine 存储到字符串变量中?
- git - 版本控制 MS Word 文件的恐怖
- azure - 如何通过 Azure DevOps 将 Blazor 应用程序部署到 Azure
- java - 有没有办法使用java流来减少一些代码噪音?
- javascript - 反应没有子组件的父组件
- php - 有没有可以美化php数组的网站?
- list - Prolog - 在其他变量的条件下构造列表
- javascript - 如何在 javascript 中对数据使用 eval() 函数?