2016-05-14 46 views
0

我有一個<td>,並希望從中提取文本,這是我需要的只是文本湯姆·克魯斯,辛普森,比爾·克林頓這是使用一個Python正每個<td>標籤內表達。提取文本

<td class="clic-cul manga" template=".woxColumnyd" maz="/ajax/blac-woxm/xom-line/expanded/2002-2012/11-05-2022/01/fam.json">Tom Cruz</td> 

<td class="clic-cul manga" template=".woxColumnx" mac="/ajax/blac-woxm/xom-line/expanded/2002-2012/11-05-2022/01/fam.json">Home Simpson</td> 

<td class="clic-cul manga" template=".woxColumnz" max="/ajax/blac-woxm/xom-line/expanded/2002-2012/11-05-2022/01/fam.json">Bill Clinton</td> 

任何想法?

更新1.如果HTML解析器是標準方式,我應該怎麼做呢?

+3

[不解析與正則表達式的HTML!(http://stackoverflow.com/a/1732454/418066) – Biffen

+3

的標準方法是使用HTML解析器和不是一個正則表達式 – polku

回答

1

我知道你問了一個只有正則表達式的解決方案,但我希望你可以考慮使用基於lxml的庫之一(比如html5lib或BeautifulSoup)來解析無效的HTML並提供訪問權限的其他更安全,更快和更簡單的方法到lxml樹。

隨着BeautifulSoup:

html = """ 
<td class="clic-cul manga" template=".woxColumnyd" maz="/ajax/blac-woxm/xom-line/expanded/2002-2012/11-05-2022/01/fam.json">Tom Cruz</td> 
<td class="clic-cul manga" template=".woxColumnx" mac="/ajax/blac-woxm/xom-line/expanded/2002-2012/11-05-2022/01/fam.json">Home Simpson</td> 
<td class="clic-cul manga" template=".woxColumnz" max="/ajax/blac-woxm/xom-line/expanded/2002-2012/11-05-2022/01/fam.json">Bill Clinton</td> 
""" 

import bs4 
doc = bs4.BeautifulSoup(html, 'lxml') 
print([el.text for el in doc.find_all('td')]) 

輸出然後

['Tom Cruz', 'Home Simpson', 'Bill Clinton'] 
0

如果你正在尋找一個班輪regex- >\u+(\s\u+)?</

IF NOT
比方說您將該html存儲在名爲的文件中。 我不知道python,但我知道紅寶石。 也許你可以做點什麼。

xfile3=File.open("dat.txt","r")  #html stored in dat.txt 
i=-2        #Logic here. For iterating i exactly to the position of names in the array 
ch= xfile3.read 
arr=ch.split(/[<,>]/)    #for splitting ch into arr whenever <or> is encountered 
while i<=100      # replace 100 to some no as it suits 
    i=i+4   
    puts arr[i]      
end 

工作證明 PROOF