0

我正在使用以下代码使用 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])

对于几百条记录,它可以提取结果。但是当涉及到数千条记录时。这需要很长时间。有人可以帮我优化这行代码吗?

4

1 回答 1

1

您可以通过以下方式改进:

  1. 调用nlp.pipe整个文件列表
  2. 禁用不必要的管道。

尝试:

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]
于 2021-01-01T12:03:10.200 回答