如何使用正则表达式 + Python 从 XML 获取指定标签属性的值? [英] How to get value of specified tag attribute from XML using regexp + Python?

查看:293
本文介绍了如何使用正则表达式 + 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("<POPULARITY\s+(?:\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.

这篇关于如何使用正则表达式 + Python 从 XML 获取指定标签属性的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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