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 中获取指定标签属性
基础教程推荐
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
