![](/img/trans.png)
[英]Python: Regular expression to extract text between any two tags in a html
[英]python regular expression find text between tags but the file is not in html or xml format
我有一個文本文件,其格式如下,並且我試圖在<doc>
標記之間獲取文本。 但是<doc>
標記重復很多次,並且文件不是標准的xml或html格式,這會引起問題。
格式:
<doc id = "some_number" url = " some_link " title = " some_title " >
text here
</doc>
//然后再說一次
<doc id = "some_number" url = " some_link " title = " some_title " >
text here
</doc>
//依此類推
我試圖使用Python中的Beautiful湯來獲取文本,但它說該對象不可調用,我猜是因為它不是html文件格式。 而且我嘗試使用正則表達式,所以我寫了
pattern = re.compile("<doc.*?>(.*?)</doc>")
pattern.findall(string_text) # string_text is my file
但找不到匹配項。
謝謝你的幫助。
您的HTML並沒有明顯的錯誤,也沒有任何理由BeautifulSoup無法解析它。 例如:
from bs4 import BeautifulSoup
s = '''
<doc id = "some_number" url = " some_link " title = " some_title " >
text here
</doc>
<doc id = "some_number" url = " some_link " title = " some_title " >
text here
</doc>'''
soup = BeautifulSoup(s)
for doc in soup.find_all('doc'):
print('{}: {}'.format(doc['title'], doc.text))
當我運行它時,它顯示的內容是:
some_title :
text here
some_title :
text here
如果我保留您在問題中遇到的C ++樣式的注釋,但在代碼部分之外,則它也可以使用。
如果“它說此對象不可調用”,則說明您的代碼顯然做錯了。 例如,如果我這樣做:
for doc in soup.find_all('doc'):
doc['title']('text')
……當然會提高:
TypeError: 'str' object is not callable
但這不是因為BS無法解析HTML,而是因為我從BS中得到了一個字符串,並試圖將其作為函數調用。
我不知道您實際做錯了什么,因為您沒有給我們看代碼,甚至沒有給您顯示確切的錯誤。
同時,如果您想知道HTML到底出了什么問題,則有三個問題。
第一個問題是您無法使用regexp解析HTML 。
第二個問題是您正在嘗試使用.*?
相配,其它事物之間,換行,右近的最頂端re
文檔,它說:
'.'
(點)在默認模式下,它匹配換行符以外的任何字符。 如果指定了DOTALL標志,則它匹配包括換行符在內的任何字符。
因此,您需要pattern = re.compile("<doc.*?>(.*?)</doc>", re.DOTALL)
。
但是,如果一個doc
可以包含另一個doc
,或者如果您在引號中包含任何會使您感到困惑的字符,或者……那么,有很多原因可能導致失敗。 這就是為什么:
第三個問題是您沒有閱讀您無法使用regexp解析HTML ,您需要閱讀它。
your_doc = """
<doc id = "some_number" url = " some_link " title = " some_title " >
text here
</doc> //then again
<doc id = "some_number" url = " some_link " title = " some_title " >
text here
</doc>
"""
from bs4 import BeautifulSoup as b
soup = b(your_doc)
specific_doc = b.find('doc', {'id': 'some number'}) #to get a doc with given id.
print specific_doc.contents #printing the text
all_docs = b.findAll('docs') # list of all doc tags.
for doc in all_docs: #printing all the texts
print 'Text in doc id:', doc['id']
print doc.contents
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.