我目前正在处理来自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']
你们知道我的代码中有什么问题吗?在代码中,字母被附加,而不是单词值?
发布于 2021-02-21 07:49:34
您不需要最后一个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()数据类型。
发布于 2021-02-21 09:24:41
或者,您可以将json转换为dataframe,并通过对话框id查找所有使用regex的操作。
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']]现在,您有了所有的对话框ids和它们的行为名称。它还可以工作,因为根据DSTC8中的Scheme表示,acts只出现在actions下。

https://stackoverflow.com/questions/66291504
复制相似问题