python使用正则提取指定的值并添加到字典

查看:487
本文介绍了python使用正则提取指定的值并添加到字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

<input class="input-xlarge focused" id="listCode" name="listCode" readonly="true" type="text" value="001">
</input>
<input class="input-xlarge focused" id="type" name="type" readonly="true" type="text" value="002">
</input>
<input class="input-xlarge focused" id="yyc" name="yyc" readonly="true" type="text" value="yyzz">
</input>


如何使用python 3.5的正则表达式获取每一行里面的name和value的值,并将name和value的值添加到字典.
最终的结果变为:

dict = {

    'listcode':'001',
    'type':'002',
    'yyc':'yyzz'
    

}

或者不用正则用beautifulsoup是否可以实现? 哪位方便,麻烦指点一二。谢谢。

解决方案

参考代码,BeautifulSoup的用法可以阅读官方文档

html = '<input class="input-xlarge focused" id="listCode" name="listCode" readonly="true" type="text" value="001"></input><input class="input-xlarge focused" id="type" name="type" readonly="true" type="text" value="002"></input><input class="input-xlarge focused" id="yyc" name="yyc" readonly="true" type="text" value="yyzz"></input>'
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, "lxml")
content = dict()
datas = soup.find_all("input", class_="input-xlarge focused")
for data in datas:
    content[data["name"]] = data["value"]

print(content)

这篇关于python使用正则提取指定的值并添加到字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆