使用正则表达式在 Python 中解析 XML [英] Parsing XML in Python with regex

查看:77
本文介绍了使用正则表达式在 Python 中解析 XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用正则表达式来解析 XML 文件(在我的情况下,这似乎是最简单的方法).

例如一行可能是:

line='PLAINSBORO, NJ 08536-1906'

要访问标签 City_State 的文本,我正在使用:

attr = re.match('>.*<', line)

但没有返回任何东西.

有人能指出我做错了什么吗?

解决方案

您通常不想使用 re.match.引用文档:

<块引用>

如果您想在字符串中的任何位置定位匹配项,请使用 search() 代替(另见 search() vs. match()).

注意:

<预><代码>>>>打印 re.match('>.*<', line)没有任何>>>print re.search('>.*<', line)<_sre.SRE_Match 对象在 0x10f666238>>>>print re.search('>.*<', line).group(0)>PLAINSBORO, NJ 08536-1906<

<小时>

此外,当您可以使用诸如 BeautifulSoup 之类的东西时,为什么还要用正则表达式解析 XML :).

<预><代码>>>>从 bs4 导入 BeautifulSoup 作为 BS>>>line='<City_State>PLAINSBORO, NJ 08536-1906</City_State>'>>>汤 = BS(线)>>>打印soup.find('city_state').text新泽西州普林斯伯勒 08536-1906

I'm trying to use regex to parse an XML file (in my case this seems the simplest way).

For example a line might be:

line='<City_State>PLAINSBORO, NJ 08536-1906</City_State>'

To access the text for the tag City_State, I'm using:

attr = re.match('>.*<', line)

but nothing is being returned.

Can someone point out what I'm doing wrong?

解决方案

You normally don't want to use re.match. Quoting from the docs:

If you want to locate a match anywhere in string, use search() instead (see also search() vs. match()).

Note:

>>> print re.match('>.*<', line)
None
>>> print re.search('>.*<', line)
<_sre.SRE_Match object at 0x10f666238>
>>> print re.search('>.*<', line).group(0)
>PLAINSBORO, NJ 08536-1906<


Also, why parse XML with regex when you can use something like BeautifulSoup :).

>>> from bs4 import BeautifulSoup as BS
>>> line='<City_State>PLAINSBORO, NJ 08536-1906</City_State>'
>>> soup = BS(line)
>>> print soup.find('city_state').text
PLAINSBORO, NJ 08536-1906

这篇关于使用正则表达式在 Python 中解析 XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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