gpt4 book ai didi

python从html中读取unicode字符

转载 作者:太空宇宙 更新时间:2023-11-03 19:18:25 24 4
gpt4 key购买 nike

我有这个脚本,它从网页读取文本:

page = urllib2.urlopen(url).read()
soup = BeautifulSoup(page);
paragraphs = soup.findAll('p');

for p in paragraphs:
content = content+p.text+" ";

在网页中我有这个字符串:

Möddinghofe

我的脚本读作:

Möddinghofe

我怎样才能按原样阅读它?

最佳答案

希望对你有帮助

from BeautifulSoup import BeautifulStoneSoup
import cgi

def HTMLEntitiesToUnicode(text):
"""Converts HTML entities to unicode. For example '&' becomes '&'."""
text = unicode(BeautifulStoneSoup(text, convertEntities=BeautifulStoneSoup.ALL_ENTITIES))
return text

def unicodeToHTMLEntities(text):
"""Converts unicode to HTML entities. For example '&' becomes '&'."""
text = cgi.escape(text).encode('ascii', 'xmlcharrefreplace')
return text

text = "&, ®, <, >, ¢, £, ¥, €, §, ©"

uni = HTMLEntitiesToUnicode(text)
htmlent = unicodeToHTMLEntities(uni)

print uni
print htmlent
# &, ®, <, >, ¢, £, ¥, €, §, ©
# &amp;, &#174;, &lt;, &gt;, &#162;, &#163;, &#165;, &#8364;, &#167;, &#169;

引用:Convert HTML entities to Unicode and vice versa

关于python从html中读取unicode字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10588666/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com