如何从BeautifulSoup输出中取消转义特殊字符?
我在处理一些特殊字符时遇到了问题,比如°和®,它们分别表示华氏度符号和注册商标符号。
当我打印包含这些特殊字符的字符串时,输出的结果是这样的:
Preheat oven to 350° F
Welcome to Lorem Ipsum Inc®
有没有办法让我输出这些字符本身,而不是它们的代码呢?请告诉我。
4 个回答
2
在Beautiful Soup 4中:
my_text = """Preheat oven to 350° F
Welcome to Lorem Ipsum Inc® """
soup = BeautifulSoup(my_text, 'html.parser')
print(soup)
结果:
Preheat oven to 350° F
Welcome to Lorem Ipsum Inc®
2
这里有一个脚本,可以宽容地处理网页中的HTML引用。它假设这些引用的格式是像°
这样的,后面会有一个分号(比如说:将烤箱预热到350° F
)。
from htmlentitydefs import name2codepoint
# Get the whitespace characters
nums_dict = {0: ' ', 1: '\t', 2: '\r', 3: '\n'}
chars_dict = dict((x, y) for y, x in nums_dict.items())
nums_dict2XML = {0: ' ', 1: '	', 2: ' ', 3: ' '}
chars_dict2XML = dict((nums_dict[i], nums_dict2XML[i]) for i in nums_dict2XML)
s = '1234567890ABCDEF'
hex_dict = {}
for i in s:
hex_dict[i.lower()] = None
hex_dict[i.upper()] = None
del s
def is_hex(s):
if not s:
return False
for i in s:
if i not in hex_dict:
return False
return True
class Unescape:
def __init__(self, s, ignore_whitespace=False):
# Converts HTML character references into a unicode string to allow manipulation
self.s = s
self.ignore_whitespace = ignore_whitespace
self.lst = self.process(ignore_whitespace)
def process(self, ignore_whitespace):
def get_char(c):
if ignore_whitespace:
return c
else:
if c in chars_dict:
return chars_dict[c]
else: return c
r = []
lst = self.s.split('&')
xx = 0
yy = 0
for item in lst:
if xx:
split = item.split(';')
if split[0].lower() in name2codepoint:
# A character reference, e.g. '&'
a = unichr(name2codepoint[split[0].lower()])
r.append(get_char(a)) # TOKEN CHECK?
r.append(';'.join(split[1:]))
elif split[0] and split[0][0] == '#' and split[0][1:].isdigit():
# A character number e.g. '4'
a = unichr(int(split[0][1:]))
r.append(get_char(a))
r.append(';'.join(split[1:]))
elif split[0] and split[0][0] == '#' and split[0][1:2].lower() == 'x' and is_hex(split[0][2:]):
# A hexadecimal encoded character
a = unichr(int(split[0][2:].lower(), 16)) # Hex -> base 16
r.append(get_char(a))
r.append(';'.join(split[1:]))
else:
r.append('&%s' % ';'.join(split))
else:
r.append(item)
xx += 1
yy += len(r[-1])
return r
def get_value(self):
# Convert back into HTML, preserving
# whitespace if self.ignore_whitespace is `False`
r = []
for i in self.lst:
if type(i) == int:
r.append(nums_dict2XML[i])
else:
r.append(i)
return ''.join(r)
def unescape(s):
# Get the string value from escaped HTML `s`, ignoring
# explicit whitespace like tabs/spaces etc
inst = Unescape(s, ignore_whitespace=True)
return ''.join(inst.lst)
if __name__ == '__main__':
print unescape('Preheat oven to 350° F')
print unescape('Welcome to Lorem Ipsum Inc®')
编辑:这里有一个更简单的解决方案,它只会把字符引用替换成字符,而不会处理&#xx;
这种引用。
from htmlentitydefs import name2codepoint
def unescape(s):
for name in name2codepoint:
s = s.replace('&%s;' % name, unichr(name2codepoint[name]))
return s
print unescape('Preheat oven to 350° F')
print unescape('Welcome to Lorem Ipsum Inc®')
8
这段内容是关于编程问题的讨论,主要涉及一些技术细节和解决方案。它可能包含了一些代码示例和解释,帮助理解如何处理特定的编程挑战。
在这里,大家分享了他们的经验和见解,试图找到最有效的方法来解决问题。讨论中可能会提到一些常见的错误和解决这些错误的技巧。
总之,这个话题是为了帮助那些在编程过程中遇到困难的人,提供一些实用的建议和解决方案。
$ python -c'from BeautifulSoup import BeautifulSoup
> print BeautifulSoup("""<html>Preheat oven to 350° F
> Welcome to Lorem Ipsum Inc®""",
> convertEntities=BeautifulSoup.HTML_ENTITIES).contents[0].string'
Preheat oven to 350° F
Welcome to Lorem Ipsum Inc®