【问题标题】:Create Python dictionary from HTML divs using attribute as ids使用属性作为 id 从 HTML div 创建 Python 字典
【发布时间】:2020-10-16 20:11:27
【问题描述】:

我在一个文件中有以下 html/xml 数据,我正在尝试使用该数据创建一个字典。

<REUTERS TOPICS="YES" LEWISSPLIT="TRAIN" CGISPLIT="TRAINING-SET" NEWID="1">
blah blah...
</REUTERS>
<REUTERS TOPICS="YES" LEWISSPLIT="TRAIN" CGISPLIT="TRAINING-SET" NEWID="2">
blah blah...
</REUTERS>
<REUTERS TOPICS="YES" LEWISSPLIT="TRAIN" CGISPLIT="TRAINING-SET" NEWID="3">
blah blah...
</REUTERS>
#many more like this...

我正在尝试将字典作为

 mydict = {1:"blah blah...", 2: "blah blah...", 3: "blah blah...", etc}

我的字典中的每个 id 编号对应于 REUTERS 标记元素中的 NEWID 属性。

到目前为止,我有这段代码,但我对如何使用 NEWID 的属性作为我的字典的键值对的键一无所知。

mydict = {} 
for reuters_file in os.listdir(reuters_folder):
    with open(reuters_folder+reuters_file) as file:
    soup = BeautifulSoup(file, "lxml")
    content = str(soup)  
    val = content.split('<REUTERS')
    mydict[int(key)] = val

【问题讨论】:

  • 如果您只是要将其转换为字符串,为什么还要使用BeautifulSoup
  • key 应该是 NEWID 吗?
  • yes key 应该是 NEWID 的值

标签: python file dictionary


【解决方案1】:
from bs4 import BeautifulSoup

soup = BeautifulSoup(xml, 'lxml')
d = {}

for reuters in soup.find_all('reuters'):
    d[reuters.get('newid')] = reuters.text

【讨论】:

  • 如何根据键值对创建字典?
  • 它说没有定义xml。您是否忘记为其导入依赖项?
  • 如果您从 repl.it 运行脚本,那么您需要添加 import lxml
  • 我已经导入了 lxml。我收到一个错误 xml is not defined
  • 这里xml是要解析的内容。它类似于您的代码中的soup = BeautifulSoup(file, "lxml")
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-14
  • 2010-12-10
  • 1970-01-01
  • 2018-04-07
  • 2014-06-26
  • 1970-01-01
相关资源
最近更新 更多