Panda数据帧的Spacy列表理解



我有一个看起来像的数据帧

Index    Text
0        When can I go to Canada?
1        Who is king Arthur?
2        Can you give me the email of Norton?

使用spacy,我试图从数据帧的每一行提取名称,这样我的输出看起来像这个

Index    Text                                     Name
0        When can I go to Canada?                 
1        Who is king Arthur?                      Arthur
2        Can you give me the email of Norton?     Norton

我已经成功地使用了以下代码

df['Name'] = [nlp(x).ents for x in df['Text']]

但它输出各种各样的实体,而不仅仅是名称。例如,我也会得到"加拿大"作为输出,这是我不想要的。所以,我修改了这个的代码

df['Name'] = [token.label_ for token in nlp(x).ents for x in df['Text']]

但突然我得到错误

NameError: name 'x' is not defined

为什么列表理解不起作用?遵循此处的代码示例https://spacy.io/

试试这个。

import spacy 
nlp = spacy.load("en_core_web_sm")
def get_persons( text ):
good_ents = {"PERSON" , "ORG"}
doc = nlp(text)
persons = [i.text for i in doc.ents if i.label_ in good_ents]
return persons 
df["name"] = df.apply( lambda x : get_persons( x["Text"] ) , axis = 1 )

最新更新