我正在尝试对文本执行实体分析,并且我想将结果放入数据框中。当前结果没有存储在字典中,也没有存储在Dataframe中。通过两个函数提取结果。
df:
ID title cur_working pos_arg neg_arg date
132 leave yes good coffee management, leadership and salary 13-04-2018
145 love it yes nice colleagues long days 14-04-2018
我有以下代码:
result = entity_analysis(df, 'neg_arg', 'ID')
#This code loops through the rows and calls the function entities_text()
def entity_analysis(df, col, idcol):
temp_dict = {}
for index, row in df.iterrows():
id = (row[idcol])
x = (row[col])
entities = entities_text(x, id)
#temp_dict.append(entities)
#final = pd.DataFrame(columns = ['id', 'name', 'type', 'salience'])
return print(entities)
def entities_text(text, id):
"""Detects entities in the text."""
client = language.LanguageServiceClient()
ent_df = {}
if isinstance(text, six.binary_type):
text = text.decode('utf-8')
# Instantiates a plain text document.
document = types.Document(
content=text,
type=enums.Document.Type.PLAIN_TEXT)
# Detects entities in the document.
entities = client.analyze_entities(document).entities
# entity types from enums.Entity.Type
entity_type = ('UNKNOWN', 'PERSON', 'LOCATION', 'ORGANIZATION',
'EVENT', 'WORK_OF_ART', 'CONSUMER_GOOD', 'OTHER')
for entity in entities:
ent_df[id] = ({
'name': [entity.name],
'type': [entity_type[entity.type]],
'salience': [entity.salience]
})
return print(ent_df)
此代码给出以下结果:
{'132': {'name': ['management'], 'type': ['OTHER'], 'salience': [0.16079013049602509]}}
{'132': {'name': ['leadership'], 'type': ['OTHER'], 'salience': [0.05074194446206093]}}
{'132': {'name': ['salary'], 'type': ['OTHER'], 'salience': [0.27505040168762207]}}
{'145': {'name': ['days'], 'type': ['OTHER'], 'salience': [0.004272154998034239]}}
我已经在函数temp_dict
中创建了final
和一个entity_analysis()
数据框。 This thread解释说,在循环中附加到数据帧效率不高。 我不知道如何高效地填充数据框。 These threads与我的问题有关,但它们说明了如何从现有数据填充数据框。当我尝试使用temp_dict.update(entities)
并返回temp_dict
时出现错误:
在entity_analysis中 temp_dict.update(实体) TypeError:“ NoneType”对象不可迭代
我希望输出如下:
ID name type salience
132 management OTHER 0.16079013049602509
132 leadership OTHER 0.05074194446206093
132 salary OTHER 0.27505040168762207
145 days OTHER 0.004272154998034239
答案 0 :(得分:0)
一种解决方案是通过您的entities
迭代创建列表列表。然后将您的列表列表输入pd.DataFrame
:
LoL = []
for entity in entities:
LoL.append([id, entity.name, entity_type[entity.type], entity.salience])
df = pd.DataFrame(LoL, columns=['ID', 'name', 'type', 'salience'])
如果您还需要当前生成的格式的字典,则可以将当前逻辑添加到for
循环中。但是,请首先检查是否需要使用两个结构来存储相同的数据。