簡體   English   中英

美麗的湯去除上標

[英]Beautiful soup remove superscripts

如何從所有文本中刪除上標? 我下面的代碼可以獲取所有可見的文本,但是腳注的上標使事情變得混亂。 如何刪除它們?

例如, Active accounts (1),(2)(1),(2)是可見的上標。

from bs4 import BeautifulSoup
from bs4.element import Comment
import requests


f_url='https://www.sec.gov/Archives/edgar/data/1633917/000163391718000094/exhibit991prq12018pypl.htm'

def tag_visible(element):
    if element.parent.name in ['style', 'script', 'head', 'title', 'meta', '[document]']:
        return False
    if isinstance(element, Comment):
        return False
    return True


def text_from_html(body):
    soup = BeautifulSoup(body, 'html.parser')
    texts = soup.findAll(text=True)
    visible_texts = filter(tag_visible, texts)  
    return u" ".join(t.strip() for t in visible_texts)

html = requests.get(f_url)
text= text_from_html(html.text)

BeautifulSoup函數find_all返回輸入中所有單個離散HTML元素的列表( find_all是在BeautifulSoup 4中使用的適當函數,優於findAll )。 下一個函數filter遍歷此列表,並刪除其回調例程返回False 回調函數將測試每個代碼段的標記名,如果它們在不需要的列表中,則返回False ,否則返回True

如果這些上標始終由正確的HTML標記sup指示,則可以將其添加到回調函數中不需要的列表中。

可能的陷阱是:

  1. 假定使用文字(在語義上正確)標簽sup ,而不是使用僅指定 vertical-align: superscript;的類或跨度vertical-align: superscript; 在其CSS中;
  2. 假定您要擺脫此上標標記中的所有元素。 如果有異常(“20 世紀 ”),你可以檢查的文本內容; 例如,僅當內容全部為數字時才刪除。 如果也有例外的是 (“A 2 = B 2 + C 2”),則必須檢查一個更寬的范圍內,或構建夾雜物/排除的白名單或黑名單。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM