How to get value of specified tag attribute from XML using regexp + Python?(如何使用 regexp + Python 从 XML 中获取指定标签属性的值?)
问题描述
我有一个解析一些 xml 的脚本.XML 包含:
I have a script that parses some xml. XML contains:
<SD TITLE="A" FLAGS="" HOST="9511.com">
<TITLE TEXT="9511 domain"/>
<ADDR STREET="Pmb#400, San Pablo Ave" CITY="Berkeley" STATE="CA" COUNTRY="US"/>
<CREATED DATE="13-Oct-1990" DAY="13" MONTH="10" YEAR="1990"/>
<OWNER NAME="9511.Org Domain Name Proxy Agents"/>
<EMAIL ADDR="proxy@9511.org"/><LANG LEX="en" CODE="us-ascii"/>
<LINKSIN NUM="75"/><SPEED TEXT="3158" PCT="17"/>
<CHILD SRATING="0"/>
</SD>
<SD>
<POPULARITY URL="9511.com/" TEXT="1417678" SOURCE="panel"/>
</SD>
如何获取标签的'TEXT'属性值(在我的例子中是1417678)?我正在使用正则表达式+Python.正则表达式字符串:
How to get the 'TEXT' attribute value of tag(in my case 1417678)? I'm using regexp+Python. Regexp string:
my_value = re.findall("POPULARITY[^d]*(d+)", xml)
我收到了9511",但我需要1417678".
It gets to me '9511' but i need '1417678'.
推荐答案
您只是匹配出现在元素名称之后的第一个十进制数字序列.在任意数量的非数字 '[^d]*'
之后的第一个数字序列 '(d+)'
是 9511
.
You are just matching the first sequence of decimal digits that occurs after the element's name. The first sequence of digits '(d+)'
after a arbitrary number of non-digits '[^d]*'
is 9511
.
为了findall
@TEXT
属性的值,这样的事情会起作用:
In order to findall
values of @TEXT
attributes, something like this would work:
my_values = re.findall("<POPULARITY(?:D+="S*")*s+TEXT="(d*)"", xml) # returning a list btw
或者,如果除了 @TEXT
之外没有其他属性将具有纯数字值:
Or, if no other attributes will have digit-only values except @TEXT
:
re.findall("<POPULARITYs+(?:S+s+)*w+="(d+)"", xml)
(?:...)
与包含的表达式匹配,但不像 (...)
那样充当可寻址组.特殊序列 S
和 D
是它们对应的小写字母的反转,分别扩展到(除了)空格和数字.
Where (?:...)
matches the embraced expression, but doesn't act as an addressable group, like (...)
. The special sequences S
and D
are the invertions of their lowercase counterparts, expanding to (anything but) whitespace and digits, respectively.
但是,正如已经提到的,正则表达式不适用于 XML,因为 XML 不是常规语言.
However, like already mentioned, regex are not meant to be used on XML, because XML is not a regular language.
这篇关于如何使用 regexp + Python 从 XML 中获取指定标签属性的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用 regexp + Python 从 XML 中获取指定标签属性


基础教程推荐
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- 包装空间模型 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 求两个直方图的卷积 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01