在两个标签之间查找单词的正则表达式
我该如何在Python中使用正则表达式来找到标签之间的单词呢?
s = """<person>John</person>went to<location>London</location>"""
......
.......
print 'person of name:' John
print 'location:' London
3 个回答
1
probably you are looking for **XML tree and elements**
XML is an inherently hierarchical data format, and the most natural way to represent it is with a tree. ET has two classes for this purpose - ElementTree represents the whole XML document as a tree, and Element represents a single node in this tree. Interactions with the whole document (reading and writing to/from files) are usually done on the ElementTree level. Interactions with a single XML element and its sub-elements are done on the Element level.
19.7.1.2. Parsing XML
We’ll be using the following XML document as the sample data for this section:
<?xml version="1.0"?>
<data>
<country name="Liechtenstein">
<rank>1</rank>
<year>2008</year>
<gdppc>141100</gdppc>
<neighbor name="Austria" direction="E"/>
<neighbor name="Switzerland" direction="W"/>
</country>
<country name="Singapore">
<rank>4</rank>
<year>2011</year>
<gdppc>59900</gdppc>
<neighbor name="Malaysia" direction="N"/>
</country>
<country name="Panama">
<rank>68</rank>
<year>2011</year>
<gdppc>13600</gdppc>
<neighbor name="Costa Rica" direction="W"/>
<neighbor name="Colombia" direction="E"/>
</country>
</data>
我们有很多方法可以导入数据。首先是从磁盘读取文件:
import xml.etree.ElementTree as ET
tree = ET.parse('country_data.xml')
root = tree.getroot()
其次是从字符串中读取数据:
root = ET.fromstring(country_data_as_string)
还有其他的Python XML和HTML解析器
https://wiki.python.org/moin/PythonXml http://docs.python.org/2/library/htmlparser.html
10
import re
# simple example
pattern = r"<person>(.*?)</person>"
string = "<person>My name is Jo</person>"
re.findall(pattern, string, flags=0)
# multiline string example
string = "<person>My name is:\n Jo</person>"
re.findall(pattern, string, flags=re.DOTALL)
这个例子只适合简单的解析。如果你想了解更多,可以看看Python官方文档中的re
模块。
如果你想解析HTML,建议你参考@sabuj-hassan的回答,不过也别忘了查看这个Stack Overflow上的好帖子。
13
你可以使用 BeautifulSoup
来解析这个HTML。
input = """"<person>John</person>went to<location>London</location>"""
soup = BeautifulSoup(input)
print soup.findAll("person")[0].renderContents()
print soup.findAll("location")[0].renderContents()
另外,在Python中用 str
作为变量名并不是个好主意,因为 str()
在Python中有其他的意思。
顺便提一下,正则表达式可以是:
import re
print re.findall("<person>(.*?)</person>", input, re.DOTALL)
print re.findall("<location>(.*?)</location>", input, re.DOTALL)