2017-06-14 17 views
0

我有一個手動的輸入文件由引文組成,每個格式爲:如何使用正則表達式從文本中提取由標籤分隔的多個引用?

<小號SID =「2」 SSID =「2」>它不同於先前的機器 基於學習的,因爲它淨入學使用來自整個 文檔的信息來對每個詞進行分類,只用一個分類器。以前涉及從整個文檔中收集信息的工作通常使用第二分類器 ,其糾正了基於主要句子的分類器的錯誤。 < /S>

下面是使用Python的re模塊我目前的做法:

citance = citance[citance.find(">")+1:citance.rfind("<")] 
fd.write(citance+"\n") 

我試圖提取了從第一關角括號(「>」)到最後的發生打開角度支架(「<」)。然而,在多個citances的情況下,作爲中間變量也輸出得到提取這種方法失敗:

它不同於以往基於機器學習的淨入學率,它使用 信息,從整個文件到每個分類字,只有 一個分類器。 </S> < S sid =「3」ssid =「3」>以前的工作涉及到 從整個文檔收集信息通常使用一個 二級分類器,它可以糾正基於句子的分類器的錯誤。

我想要的輸出:

它不同於以前的機器學習爲主的淨入學率,它使用 信息,從整個文檔的每個詞進行分類,只有 一個分類。涉及 所述的從整個文件的信息收集先前的工作經常使用 二級分類器,其校正的主 sentence-基於分類器的錯誤。

我怎樣才能正確地實現這一點?

回答

1

我會去與蟒蛇正則表達式模塊:通過做re

re.findall(r'\">(.*?)<', text_to_parse) 

這個方法會從一個到多個報價回來,但你可以加入後他們,如果你想有一個統一的文本(" ".join(....)

1

而是重新使用的模塊,看看到bs4庫。

這是一個XML/HTML解析,從而你可以得到標記之間的一切。

對你來說,這將是這樣的:

from bs4 import BeautifulSoup 

xml_text = '< S sid ="2" ssid = "2">It differs from previous machine learning-based NERs in that it uses information from the whole document to classify each word, with just one classifier.< /S>< S sid ="3" ssid = "3">Previous work that involves the gathering of information from the whole document often uses a secondary classifier, which corrects the mistakes of a primary sentence- based classifier.< /S>' 

text_soup = BeautifulSoup(xml_text, 'lxml') 

output = text_soup.find_all('S', attrs = {'sid': '2'}) 

輸出將包含文本:

它不同於以前的機器學習爲主的淨入學率,它使用從整個文檔資料用一個分類器對每個詞進行分類。

而且,如果你只是想刪除HTML標籤:

import re 

xml_text = '< S sid ="2" ssid = "2">It differs from previous machine learning-based NERs in that it uses information from the whole document to classify each word, with just one classifier.< /S>< S sid ="3" ssid = "3">Previous work that involves the gathering of information from the whole document often uses a secondary classifier, which corrects the mistakes of a primary sentence- based classifier.< /S>' 

re.sub('<.*?>', '', html_text) 

將做的工作。

0

我認爲這就是你要找的。

import re 

string = ">here is some text<>here is some more text<" 
matches = re.findall(">(.*?)<", string) 
for match in matches: print match 

看起來好像你有一個問題得到太多的結果。 「這裏是更多文字<」的匹配可以來自字符串中的第一個字符到最後一個字符,因爲它們是「>」和「<」,而忽略中間的字符。 '。*?'成語會使它找到最大的點擊次數。

相關問題