如何从所有文本中删除上标?我下面的代码可以获取所有可见文本,但是脚注的上标把事情弄乱了。我该如何删除它们?
例如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 https://www.crummy.com/software/BeautifulSoup/bs4/doc/#find-all返回输入中所有单个离散 HTML 元素的列表 (find_all
是在 BeautifulSoup 4 中使用的正确函数,并且优先于findAll
)。下一个函数,filter https://docs.python.org/3/library/functions.html#filter,遍历此列表并删除其回调例程返回的项目False
。回调函数测试每个片段的标签名称并返回False
如果它在不想要的列表中,True
否则。
如果这些上标始终由正确的 HTML 标记指示sup
然后您可以将其添加到回调函数中的不需要列表中。
可能的陷阱是:
- 假设文字(语义正确)标签
sup
使用,而不是,例如,仅仅使用一个类或一个跨度指定 vertical-align: superscript;
在它的 CSS 中;
- It is assumed that you want to get rid of all elements that are in this superscript tag. If there are exceptions ("the 20th century"), you can check the text contents; for example, only remove if its contents are all numerical. If there are exceptions to that ("a2 = b2 + c2"), you will have to check for a wider context, or build a whitelist or blacklist of inclusions/exclusions.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)