在两个标记之间查找单词的正则表达式

2024-04-26 00:19:08 发布

您现在位置:Python中文网/ 问答频道 /正文

如何在python中使用regex在标记之间查找单词?

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

Tags: oftoname标记locationjohn单词regex
3条回答
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

希望有帮助

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/PythonXmlhttp://docs.python.org/2/library/htmlparser.html

您可以使用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中意味着不同的东西。

顺便说一下,regex可以是:

import re
print re.findall("<person>(.*?)</person>", input)
print re.findall("<location>(.*?)</location>", input)

相关问题 更多 >