2016-06-21 108 views
1

我想通过解析字符串解析和创建字典蟒蛇

<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

为什么不尝试用空格拆分输入并使用list.index()来查找''='',得到索引(比如说a)并用le生成dict英尺和右操作数(即在列表中,a-1,a + 1)等号? (因为我不熟悉正则表达式) – YiFei

回答

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'}