问题描述
限时送ChatGPT账号..我正在尝试使用正则表达式来解析 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 :).
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屋!
更多推荐
[db:关键词]
发布评论