gpt4 book ai didi

python - 迭代 python 字典以仅检索所需的行

转载 作者:行者123 更新时间:2023-12-01 03:32:54 26 4
gpt4 key购买 nike

我从外部源获取 HTML 表格格式的数据 -

from xml.etree import ElementTree as ET

s = """<table>
<tr><th>Release</th><th>REFDB</th><th>URL</th></tr>
<tr><td>3.7.3</td><td>12345</td><td>http://google.com</td></tr>
<tr><td>3.7.4</td><td>456789</td><td>http://foo.com</td></tr>
</table>
"""

用于将 html 表转换为字典

table = ET.XML(s)
rows = iter(table)
headers = [col.text for col in next(rows)]
for row in rows:
values = [col.text for col in row]
out = dict(zip(headers, values))

现在我的预期输出如下,因为我将从命令行参数传递发布版本。$ python myscript.py 3.7.3 (我有一个代码)我正在寻找一种解决方案,当它找到特定的发布版本时循环遍历字典 - 在我的例子中它是 3.7.3

Release Version - 3.7.3
REFDB - 12345
URL - http://google.com

最佳答案

你不需要字典。只需解析每一行的内容并查看发布版本是否与您的输入匹配:

#coding:utf-8

import sys
from lxml import html

if len(sys.argv) != 2:
raise Exception("Please provide release version only")

release_input = sys.argv[1].strip()

data = """<table>
<tr><th>Release</th><th>REFDB</th><th>URL</th></tr>
<tr><td>3.7.3</td><td>12345</td><td>http://google.com</td></tr>
<tr><td>3.7.4</td><td>456789</td><td>http://foo.com</td></tr>
</table>
"""

tree = html.fromstring(data)
for row in tree.xpath('//tr')[1:]:
release, refbd, url = row.xpath('.//td/text()')
if release_input == release:
print("Release Version - {}".format(release))
print("REFBD - {}".format(refbd))
print("URL - {}".format(url))
break

print("{} release version wasn't found".format(release_input))

关于python - 迭代 python 字典以仅检索所需的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40689327/

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