解析并创建字典python

用户名

我想通过解析字符串来创建字典

<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)

但是,我应该如何调整脚本以处理标记中的多个属性对呢?

谢谢

ec

可能是出于教育原因,这是一个替代选项-您可以将这种字符串传递到宽大的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'}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章