如何使用 regexp + Python 从 XML 中获取指定标签属性的值?

2022-01-10 00:00:00 python python-2.7 regex xml-parsing

问题描述

我有一个解析一些 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)

(?:...) 与包含的表达式匹配,但不像 (...) 那样充当可寻址组.特殊序列 SD 是它们对应的小写字母的反转,分别扩展到(除了)空格和数字.

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.

相关文章