我是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”模式,但如果我想,我可以更改语言
提前感谢:)
我建议使用
这里,
(\S)([/:()])
正则表达式用于匹配任何非空白(将其捕获到组1中),然后匹配/
、:
、(
或)
(将其捕获到组2中),然后re.sub
在这两个组之间插入一个空格^\d+[,.]\d+$
正则表达式匹配包含浮点值的完整标记文本,%
是下一个标记文本(因为数字和%
被模型拆分为单独的标记)完整的Python代码片段:
输出:
相关问题 更多 >
编程相关推荐