我想通过解析字符串来创建一个字典
<brns ret = "Herld" other = "very">
<brna name = "ame1">
我想创建一个具有以下键值对的字典:
dict = {'brnsret': 'Herld',
'brnsother':'very',
'brnaname':'ame1'}
我有一个可以处理此问题的工作脚本:
<brns ret = "Herld">
<brna name = "ame1">
我的代码生成字典:
match_tag = re.search('<(\w+)\s(\w+) = \"(\w+)\">', each_par_line)
if match_tag is not None:
dict_tag[match_tag.group(1)+match_tag.group(2)] = match_tag.group(3)
但是我应该如何调整我的脚本来处理标签中的多个属性对?
谢谢
答案 0 :(得分:2)
另一种选择,可能只是出于教育原因 - 您可以将此类字符串传递给宽松的 HTML解析器,如BeautifulSoup
:
from bs4 import BeautifulSoup
data = """
<brns ret = "Herld" other = "very">
<brna name = "ame1">
"""
d = {tag.name + attr: value
for tag in BeautifulSoup(data, "html.parser")()
for attr, value in tag.attrs.items()}
print(d)
打印:
{'brnaname': 'ame1', 'brnsother': 'very', 'brnsret': 'Herld'}