正则表达式在两个标签之间找到单词

时间:2014-03-07 10:47:04

标签: python regex

如何在python中使用正则表达式来查找标签之间的单词?

s = """<person>John</person>went to<location>London</location>"""
......
.......
print 'person of name:' John
print 'location:' London 

3 个答案:

答案 0 :(得分:7)

您可以使用BeautifulSoup进行此html解析。

input = """"<person>John</person>went to<location>London</london>"""
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)
print re.findall("<location>(.*?)</location>", input)

答案 1 :(得分:4)

import re

pattern = r"<person>(.*?)</person>"
re.findall(pattern, str, flags=0) #you may need to add flags= re.DOTALL if your str is multiline

希望有所帮助

答案 2 :(得分: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&amp; Html解析器

https://wiki.python.org/moin/PythonXml http://docs.python.org/2/library/htmlparser.html