我有4样东西。你知道吗
item['bigCtgr'] = 'item'
item['smaCtgr'] = 'food'
item['ssCtgr'] = 'apple'
item['sCtgr'] = 'red'
我会多次添加到这个项目中。 所以我想做这样的结构。 类似于分类
{"item" :
{"food":
{"apple":
{"green":NULL},
{"red":NULL}},
{"banana":
{"yellow":NULL},
{"green":NULL}},
}
{"sweet":
{"candy":
{"yellow":NULL}}
}
}
但我的代码不起作用,我也不知道为什么。你知道吗
class CategoryPipeline(object):
global ctgr
ctgr = {}
def __init__(self):
global file
file = open("test.json","w")
def process_item(self, item, spider):
if item['bigCtgr'] not in ctgr.keys():
ctgr[item['bigCtgr']] = {item['smaCtgr']: {item['ssCtgr'] : {item['sCtgr'] : 'NULL'}}}
if item['smaCtgr'] not in ctgr[item['bigCtgr']].keys():
ctgr[item['bigCtgr']][item['smaCtgr']] = {item['ssCtgr']: {item['sCtgr'] : 'NULL'}}
elif item['ssCtgr'] not in ctgr[item['bigCtgr']][item['smaCtgr']].keys():
ctgr[item['bigCtgr']][item['smaCtgr']][item['ssCtgr']] = {item['sCtgr'] : 'NULL'}
else:
ctgr[item['bigCtgr']][item['smaCtgr']][item['ssCtgr']][item['sCtgr']] = 'NULL'
def __del__(self):
b = json.dumps(ctgr, ensure_ascii=False).encode('utf-8')
file.write(b)
file.write('\n')
file.close()
我该怎么做代码?你知道吗
我还发现了这个函数
我用dict和
__missing__
函数实现了一个树。如果不存在,则添加节点你可以这样使用它
相关问题 更多 >
编程相关推荐