2014-03-07 72 views
0

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

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

可能更好地使用HTML /像BeautifulSoup的xml解析器 –

+0

任何标签或只是人物和位置标签? – dorvak

+1

请参阅着名的http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags – isedev

回答

3

您可以使用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()一个很好的做法意味着蟒蛇不同的事情。

顺便说一句,正则表达式可以是:

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

为什么使用renderContents?另外,我会更新到bs4。 – Blender

+0

@Blender我不知道如何消除标签。你可以帮我吗? –

+1

'.string'是你所需要的。此外,'.find('person')'相当于'.findAll('person')[0]'。 – Blender

1
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 

希望它可以帮助

0
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

相关问题