我目前正在使用python中內置的lxml.etree通過xml檔案進行決議。我遇到了一些關于提取元素標簽中的文本的問題。
以下是我當前問題的示例代碼。
<body> <P> Title 1 </P> This is a sample text after the the p tag that contains the title. </body>
<body> sample text sample text sample text sample text <P> not a title </P> This is sample text after a p tag that does not contain a title. </body>
<body> sample text sample text <P> not a title </P> This is sample text after a p tag that does not contain a title. <P> Another P tag not containing a title </P></body>
<body> <P> Title 2 </P> This is a sample text after the the p tag that contains the title. </body>
我的沖突如下:
如果有標題,我正在使用第一個 P 標簽來捕獲每個正文標簽的標題。標題(在大多數情況下)是緊跟在 body 標記之后的第一個 P 標記(因此示例代碼第 1 行和第 4 行)。我沒有特定的標題名稱串列,這就是我使用這種方法來捕獲標題的原因。
問題是當正文中不存在標題但正文標記內的某處有 P 標記時,它不在正文標記之后(因此代碼行 2 和 3),程式將第一個 P 標記和其中的文本作為標題. 在這種情況下,相應的 P 標簽不是標題,不應被視為一個,但由于它被視為一個,因此該 P 標簽之前的任何文本都將被忽略并且不會被寫入新的文本檔案。
為了進一步說明,以下是寫入文本檔案的內容。
Title 1 : This is a sample text after the the p tag that contains the title.
not a title : This is sample text after a p tag that does not contain a title.
not a title : This is sample text after a p tag that does not contain a title. Another P tag not containing a title
Title 2 : This is a sample text after the the p tag that contains the title.
所需的輸出到文本檔案
Title 1 : This is a sample text after the the p tag that contains the title.
sample text sample text sample text sample text not a title This is sample text after a p tag that does not contain a title.
sample text sample text not a title This is sample text after a p tag that does not contain a title. Another P tag not containing a title
Title 2 : This is a sample text after the the p tag that contains the title.
可能的解決方案:
1.有什么辦法可以找到第一個P標簽的位置。如果第一個 P 標簽存在于 body 標簽之后,我想保留它。我想剝離但保留文本的任何其他 P 標簽。我可以通過使用 lxml.etree 中的內置函式來做到這一點
strip_tags()
非常感謝您對此問題或其他可能的解決方案的任何見解......提前感謝您!
uj5u.com熱心網友回復:
我能夠使用BeautifulSoup和正則運算式識別標題。
from bs4 import BeautifulSoup as soup
from lxml import etree
import re
markup = """<body> <P> Title 1 </P> This is a sample text after the the p tag that contains the title. </body>
<body> sample text sample text sample text sample text <P> not a title </P> This is sample text after a p tag that does not contain a title. </body>
<body> sample text sample text <P> not a title </P> This is sample text after a p tag that does not contain a title. <P> Another P tag not containing a title </P></body>
<body> <P> Title 2 </P> This is a sample text after the the p tag that contains the title. </body>"""
soup = soup(markup,'html.parser')
titles = soup.select('body')
for title in titles:
groups = re.search('<body> *<p>', str(title))
has_title = groups != None
if has_title:
print(title.p.text)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/460774.html
