为什么附加字母而不是单词?

Why are the letters appended instead of the word?

我目前正在处理来自 DSTC8 模式对话的 JSON 文件:https://github.com/google-research-datasets/dstc8-schema-guided-dialogue

我正在尝试为每个对话提取键 'act' 的值,我的代码如下所示:

with open('path/dialogues_001.json', 'r') as f:
data = json.load(f)

    col = []
    #Looping through each dialogue
    for i in data:
        row = []
        x.append(q)
         #For every turns, we will loop through the 'frames' and 'actions'
         for j in i['turns']:
             for k in j['frames']:
                 for l in k['actions']:
                    #Looping through the key ; 'act'
                    for m in l['act']:
                        q.append(m)

print(x[0])

追加有效,但结果写为

['I', 'N', 'F', 'O', 'R', 'M', 'I', 'N', 'F', 'O', 'R', 'M', 'I', 'N', 'F', 'O', 'R', 'M', '_', 'I', 'N', 'T', 'E', 'N', 'T', 'R', 'E', 'Q', 'U', 'E', 'S', 'T']

而不是['INFORM', 'INFORM, INFORM_INTENT, 'REQUEST']

你们知道我的代码中附加字母而不是单词值出了什么问题吗?

您不需要最后一个 for 循环,因为它正在迭代为键 act.

找到的值的字母

此外,如果您使用有意义的对象名称将有助于更好地维护代码:

import json

acts = []
with open('inp.json', 'r') as f:
    data = json.load(f)

    for dialogue in data:
        for turn in dialogue.get('turns', []):
            for frame in turn.get('frames', []):
                for action in frame.get('actions', {}):
                    act = action.get('act')
                    acts.append(act)
print(acts)

输出子集:

['INFORM', 'INFORM_INTENT', 'REQUEST', 'REQUEST', 'INFORM']

注意:如果您只想要唯一的行为名称,您可能需要使用 set() 数据类型。

或者,您可以将 json 更改为 dataframe 并通过对话 ID 查找所有使用正则表达式的行为。

import pandas as pd
import re

df = pd.read_json('path/dialogues_001.json')
df.turns = df.turns.apply(str)
df['acts'] = [re.findall(r"'act': '(\w+)'", row) for row in df['turns']]

现在您拥有所有对话 ID 及其行为名称。它也有效,因为根据 DSTC8, acts only appear under actions.

中的方案表示