问题描述
我正在使用 following 代码使用 lambda 提取命名实体。
df['Place'] = df['Text'].apply(lambda x: [entity.text for entity in nlp(x).ents if entity.label_ == 'GPE'])
和
df['Text'].apply(lambda x: ([entity.text for entity in nlp(x).ents if entity.label_ == 'GPE'] or [''])[0])
对于几百条记录,它可以提取结果。但是当涉及到数千条记录时。它几乎需要永远。有人可以帮我优化这行代码吗?
解决方法
您可以通过以下方式改进:
- 对整个文档列表调用
nlp.pipe
- 禁用不必要的管道。
试试:
import spacy
nlp = spacy.load("en_core_web_md",disable = ["tagger","parser"])
df = pd.DataFrame({"Text":["this is a text about Germany","this is another about Trump"]})
texts = df["Text"].to_list()
ents = []
for doc in nlp.pipe(texts):
for ent in doc.ents:
if ent.label_ == "GPE":
ents.append(ent)
print(ents)
[Germany]