gpt4 book ai didi

python - 如何将 html `abbr` 标签文本转换为 Python 中括号中的文本?

转载 作者:太空狗 更新时间:2023-10-30 01:24:29 24 4
gpt4 key购买 nike

我需要将由外部源生成的数百个 html 句子转换为可读文本,并且我对 abbr 标记的转换有疑问。下面是一个例子:

from bs4 import BeautifulSoup
text = "<abbr title=\"World Health Organization\" style=\"color:blue\">WHO</abbr> is a specialized agency of the <abbr title=\"United Nations\" style=\"color:#CCCC00\">UN</abbr>."
print (BeautifulSoup(text).get_text())

此代码返回“WHO 是联合国的一个专门机构。”。但是,我想要的是“WHO(世界卫生组织)是联合国(联合国)的一个专门机构。”有没有办法做到这一点?也许是另一个模块而不是 BeautifulSoup?

最佳答案

您可以遍历 soup.contents 中的元素:

from bs4 import BeautifulSoup as soup
text = "<abbr title=\"World Health Organization\" style=\"color:blue\">WHO</abbr> is a specialized agency of the <abbr title=\"United Nations\" style=\"color:#CCCC00\">UN</abbr>."
d = ''.join(str(i) if i.name is None else f'{i.text} ({i["title"]})' for i in soup(text, 'html.parser').contents)

输出:

'WHO (World Health Organization) is a specialized agency of the UN (United Nations).'

关于python - 如何将 html `abbr` 标签文本转换为 Python 中括号中的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58054852/

24 4 0