如何在Python中将HTML中的`abbr`标签文本转换为括号中的文本?

4

我需要将外部源生成的数百个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 is a specialized agency of the UN."。但是我想要的是"WHO(世界卫生组织)是联合国(United Nations)的专门机构。" 有没有其他模块可以实现这个功能,而不是使用BeautifulSoup?
2个回答

1
你可以遍历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).'

0

可能是历史上最糟糕的算法之一:

import re
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>."
soup = BeautifulSoup(text, 'html.parser')
inside_abbrs = soup.find_all('abbr')

string_out = ''

for i in inside_abbrs: 
  s = BeautifulSoup(str(i), 'html.parser')
  t = s.find('abbr').attrs['title']
  split_soup = re.findall(r"[\w]+|[.,!?;]", soup.text)
  bind_caps = ''.join(re.findall(r'[A-Z]', t))

  for word in split_soup:
    if word == bind_caps:
      string_out += word + " (" + t + ") " 
      break
    else:
      string_out += word + " "

string_out = string_out.strip()
string_out += '.'
print(string_out)

输出

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接