gpt4 book ai didi

python - 如何在 python/mongodb/elementTree 中将列表项转换为相应的字典

转载 作者:太空宇宙 更新时间:2023-11-04 07:45:06 24 4
gpt4 key购买 nike

我是 python 的新手。现在是 Python 2.7

我在 elementTree 中处理 xml 并使用 Mongodb。我要处理的 XML 是“http://www.sec.gov/Archives/edgar/usgaap.rss.xml”下面是代码:

import os
import cgi
import sqlite3 as litefire
import sys
sys.stderr = sys.stdout
from xml.etree import ElementTree
from pymongo import Connection
connc2=Connection('localhost',27017)
db2=connc2['rss']
rss=db2.rss

xmlrss=[]
treexsdr = ElementTree.parse('xbrlrss_all.xml')
i=0
k=0
o=0
o2=0
iter = treexsdr.getiterator()

for element in iter:
if element.tag:
o=i+k
xmlname=element.tag
if element.keys():
attributedict = dict(element.items())
for name, value in element.items():
krishna=element.items()
if element.text:
text = element.text

xmlnamelist={"xmlname":xmlname,"text":text,"ownid":o,"parentid":o2,"xmlattkeys":{k:v for k,v in krishna}}

xmlrss.append(xmlnamelist)

if element.getchildren():
o2=o
for child in element:
k=k+1
i=i+1

rss.insert(xmlrss)

当我应用 krishna=dict(element.items()) 时,我在 IDE 中收到如下错误消息:

Message File Name   Line    Position    
Traceback
<module> D:\test\mongo_rss.py 44
insert C:\Python27\lib\site-packages\pymongo\collection.py 312
InvalidDocument: key '{http://www.sec.gov/Archives/edgar}file' must not contain '.'

如果 krishna=element.items(),那么在 mongodb 中我得到:

{
"_id" : ObjectId("4f69bb6e17ea930fd803a958"),
"text" : "en-us",
"xmlname" : "language",
"xmlattkeys" : [["href", "http://www.sec.gov/Archives/edgar/xbrlrss.all.xml"], ["type", "application/rss+xml"], ["rel", "self"]],
"parentid" : 2,
"ownid" : 16
}

但是我想要

{
"_id" : ObjectId("4f69bb6e17ea930fd803a958"),
"text" : "en-us",
"xmlname" : "language",
"xmlattkeys" : {"href":"http://www.sec.gov/Archives/edgar/xbrlrss.all.xml", "type":"application/rss+xml", "rel":"self"},
"parentid" : 2,
"ownid" : 16
}

请帮助我做到这一点。

最佳答案

代替

for name, value in element.items():
krishna=element.items()

krishna = dict(element.items())

(也许考虑为该变量使用更具描述性的名称。)

关于python - 如何在 python/mongodb/elementTree 中将列表项转换为相应的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9804031/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com