【发布时间】:2019-11-22 21:21:37
【问题描述】:
我一直在使用 SpaCy 进行 NLP 项目,以获取所有实体的左侧和右侧单词并将它们转储为 JSON 格式。
这是我尝试过的功能:
def __init__(self):
self.new_side_words_json = dict()
def side_words(self, text):
words = nlp(text).ents[0]
side_words_json = [{'LeftSideWord': str(words[entity.start - 1]),
'Entity': str(entity),
'RightSideWord': str(words[entity.end])}
if not words[entity.start - 1].is_punct
and not words[entity.start - 1].is_space
and not words[entity.end].is_punct
and not words[entity.end].is_space
else
{'LeftSideWord': str(words[entity.start - 2]),
'Entity': str(entity),
'RightSideWord': str(words[entity.end + 1])}
for entity in nlp(text).ents]
self.new_side_words_json['SideWords'] = side_words_json
在某些情况下,此算法有效。但是,在我看来,这是一个非常丑陋的解决方案,因为它对条件的控制不够。该算法高度依赖文本格式。我想构建一些适用于每个文档的可靠的东西。
我的意思是,在文本文件中,可以有很多标点符号或空格。我只是控制上下两个级别。
我想做的是,创建一个算法来查找实体之前和之后的有意义的单词,但不是标点符号或空格,甚至可能不是停用词。
如何调整此算法以获取所有实体的上一个和下一个有意义的单词?
【问题讨论】:
标签: python-3.x spacy