gpt4 book ai didi

python - 在 Python 中向字典添加元素

转载 作者:行者123 更新时间:2023-11-28 22:41:02 25 4
gpt4 key购买 nike

我已经使用 BeautifulSoup 解析器来解析 xml 文档。这是下面的代码。我想将所有元素放入一个字典中。

import requests
from bs4 import BeautifulSoup

f = open('/home/soundarya/Desktop/mv-v18-1526.nxml','r')

d = BeautifulSoup(f.read())

s = d.find('journal-meta')

j = s.findAll('journal-id')
print s.find('journal-title').renderContents()

print s.find('issn').renderContents()

print s.find('publisher-name').renderContents()

for x in j:
print x.renderContents()

我得到了这个作为元素的输出:

/usr/local/lib/python2.7/dist-packages/bs4/__init__.py:166: UserWarning: No parser was explicitly specified, so I'm using the best available HTML parser for this system ("lxml"). This usually isn't a problem, but if you run this code on another system, or in a different virtual environment, it may use a different parser and behave differently.

To get rid of this warning, change this:

BeautifulSoup([your markup])

to this:

BeautifulSoup([your markup], "lxml")

markup_type=markup_type))
**Molecular Vision
1090-0535
Molecular Vision
Mol Vis
Mol. Vis
MV**

我试过使用 like :

import requests
from bs4 import BeautifulSoup

f = open('/home/soundarya/Desktop/mv-v18-1526.nxml','r')

d = BeautifulSoup(f.read())

a = {}
a['journal-meta'] = d.find('journal-meta')
a['journal-id'] = a.find('journal-id')
a['journal-title'] = a.find('journal-title').renderContents()
a['issn'] = a.find('issn').renderContents()
a['publisher-name'] = a.find('publisher-name').renderContents()

for x in a:
print x.renderContents()

我收到这个错误:

AttributeError: 'dict' object has no attribute 'find'

帮我把元素放到字典里。

最佳答案

a['journal-id'] = a.find('journal-id')

我想你想使用变量 d:

a['journal-id'] = d.find('journal-id')

一般来说,尽量使用更具描述性的变量名。

关于python - 在 Python 中向字典添加元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33013567/

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