2014-03-07 99 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

相關問題