从 spacy 对象中删除命名实体
Remove Named Entities from the spacy object
我正在尝试使用 Spacy 从文档中删除命名实体。我没有发现任何识别命名实体的麻烦。使用此代码:
ne = [(ent.text, ent.label_) for ent in doc.ents]
print(ne)
persons = [ent.text for ent in doc.ents if ent.label_ == 'PERSON']
print(persons)
输出:
'Timothy D. Cook',
'Peter',
'Peter',
'Benjamin A. Reitzes',
'Timothy D. Cook',
'Steve Milunovich',
'Steven Mark Milunovich',
'Peter',
'Luca Maestri'
但后来我尝试使用这个块从文档中实际删除它们:
text_no_namedentities = []
ents = [e.text for e in doc.ents]
for item in doc:
if item.text in ents:
pass
else:
text_no_namedentities.append(item.text)
print(" ".join(text_no_namedentities))
它不起作用,因为 NE 是 n-gram。如果我只检查一小块 spacy 对象的内容,它如下所示:
for item in doc:
print(item.text)
iPad
has
a
78
%
Steve
Milunovich
share
of
the
U.S.
commercial
tablet
market
所以 spacy 对象被标记化了。因此,我无法使用上面的代码删除 NE。关于如何从对象中删除所有命名实体的任何想法?
您要检查的条件是
if item.ent_type:
如果 item
("token") 是命名实体的一部分,这将计算为 True
。 token.ent_type
将是实体实际类型的哈希 ID,您可以使用 token.ent_type_
(注意 _)进行查询。
这将是我要使用的代码:
text_no_namedentities = ""
for token in doc:
if not token.ent_type:
text_no_namedentities += token.text
if token.whitespace_:
text_no_namedentities += " "
请注意,您可以使用 token.whitespace_
来确定原始句子中的原始标记是否后跟 space。
有关详细信息,请参阅 Token
here 上的文档。
仅供参考 - 将来,包含代码的最小工作片段会更方便,而不仅仅是其中的一部分。
我正在尝试使用 Spacy 从文档中删除命名实体。我没有发现任何识别命名实体的麻烦。使用此代码:
ne = [(ent.text, ent.label_) for ent in doc.ents]
print(ne)
persons = [ent.text for ent in doc.ents if ent.label_ == 'PERSON']
print(persons)
输出:
'Timothy D. Cook',
'Peter',
'Peter',
'Benjamin A. Reitzes',
'Timothy D. Cook',
'Steve Milunovich',
'Steven Mark Milunovich',
'Peter',
'Luca Maestri'
但后来我尝试使用这个块从文档中实际删除它们:
text_no_namedentities = []
ents = [e.text for e in doc.ents]
for item in doc:
if item.text in ents:
pass
else:
text_no_namedentities.append(item.text)
print(" ".join(text_no_namedentities))
它不起作用,因为 NE 是 n-gram。如果我只检查一小块 spacy 对象的内容,它如下所示:
for item in doc:
print(item.text)
iPad
has
a
78
%
Steve
Milunovich
share
of
the
U.S.
commercial
tablet
market
所以 spacy 对象被标记化了。因此,我无法使用上面的代码删除 NE。关于如何从对象中删除所有命名实体的任何想法?
您要检查的条件是
if item.ent_type:
如果 item
("token") 是命名实体的一部分,这将计算为 True
。 token.ent_type
将是实体实际类型的哈希 ID,您可以使用 token.ent_type_
(注意 _)进行查询。
这将是我要使用的代码:
text_no_namedentities = ""
for token in doc:
if not token.ent_type:
text_no_namedentities += token.text
if token.whitespace_:
text_no_namedentities += " "
请注意,您可以使用 token.whitespace_
来确定原始句子中的原始标记是否后跟 space。
有关详细信息,请参阅 Token
here 上的文档。
仅供参考 - 将来,包含代码的最小工作片段会更方便,而不仅仅是其中的一部分。