【发布时间】:2016-12-16 02:36:51
【问题描述】:
确定网页文本中的编码最合适的方法是什么。我处理各种语言的网页并使用 Python 和“requests”库。最终目标是能够使用一些用于文本挖掘项目的文本提取库来获得干净的文本
resp = requests.get(url)
现在我知道我们有以下选择:
1)
from requests.utils import get_encoding_from_headers
encoding = get_encoding_from_headers(resp.headers)
html = (resp.content).decode(encoding)
2)
from requests_toolbelt.utils.deprecated import get_encodings_from_content
encoding = get_encodings_from_content(resp.content)
html = (resp.content).decode(encoding)
3)
from requests_toolbelt.utils.deprecated import get_encodings_from_content
html = get_unicode_from_response(resp)
我处理了大约 1000 个网址,并期望 1) 和 2) 相同,但有 20% 的情况并非如此。在这 20% 的情况下,(1)会给出“ISO-8859-1”,从代码来看意味着它没有在标题中找到字符集,(2)大多给出“utf8”
现在有人对此有一些经验,知道其中最合适的技术是什么,或者是否存在更好更清洁的方法?
【问题讨论】:
-
感谢@DhiaTN 的更正
标签: python character-encoding nlp python-requests text-extraction