2

我正在尝试对文本执行实体分析,我想将结果放入数据框中。目前,结果既不存储在字典中,也不存储在 Dataframe 中。使用两个函数提取结果。

东风:

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了一个数据框。该线程解释了在循环中附加到数据帧效率不高。我不知道如何以有效的方式填充数据框这些线程与我的问题有关,但它们解释了如何从现有数据填充数据框。当我尝试使用并返回时出现错误:finalentity_analysis() temp_dict.update(entities)temp_dict

在 entity_analysis temp_dict.update(entities) TypeError: 'NoneType' object is not iterable

我希望输出是这样的:

ID          name                  type                salience
132         management            OTHER               0.16079013049602509 
132         leadership            OTHER               0.05074194446206093 
132         salary                OTHER               0.27505040168762207 
145         days                  OTHER               0.004272154998034239 
4

1 回答 1

1

一种解决方案是通过您的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循环中。但是,首先检查是否需要使用两个结构来存储相同的数据。

于 2018-06-26T09:05:45.053 回答