python - 如何更改Python数组的编码?

标签 python python-2.7 web-scraping character-encoding beautifulsoup

我使用以下代码从中文网站上抓取表格。效果很好。但似乎我存储在列表中的内容没有正确显示。

import requests
from bs4 import BeautifulSoup
import pandas as pd

x = requests.get('http://www.sohu.com/a/79780904_126549')
bs = BeautifulSoup(x.text,'lxml')

clg_list = []

for tr in bs.find_all('tr'):
    tds = tr.find_all('td')
    for i in range(len(tds)):
       clg_list.append(tds[i].text)
       print(tds[i].text)

当我打印文本时,它显示汉字。但是当我打印出列表时,它显示\u4e00\u671f\uff0834\u6240\uff09'。我不确定是否应该更改编码或其他错误。

最佳答案

在这种情况下没有任何问题。

当您打印 python 列表时,python 会对列表的每个元素调用 repr。在 python2 中,unicode 字符串的 repr 显示组成该字符串的字符的 unicode 代码点。

>>> c = clg_list[0]
>>> c # Ask the interpreter to display the repr of c
u'\u201c985\u201d\u5de5\u7a0b\u5927\u5b66\u540d\u5355\uff08\u622a\u6b62\u52302011\u5e743\u670831\u65e5\uff09'

但是,如果您打印该字符串,Python 会使用文本编码(例如 utf-8)对 unicode 字符串进行编码,并且您的计算机会显示与该编码匹配的字符。

>>> print c
“985”工程大学名单(截止到2011年3月31日)

请注意,在 python3 中打印列表将按照您的预期显示中文字符,因为 python3 具有更好的 unicode 处理能力。

关于python - 如何更改Python数组的编码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47881857/

相关文章:

python - 舍入问题

Python "private"函数编码约定

python-2.7 - Ubuntu 和 Ironpython : What paths to add to sys. 路径以及如何导入 fcntl 模块?

node.js - 我在安装 noodle.js 时遇到此错误

r - 如何从 Yahoo! 抓取关键统计数据使用 R 进行财务?

python - Pandas scatter_matrix 中的类标签

python - 嵌套到 Python 中的动态深度

python - Django 模型可以实例化的最大对象数量?

java - 是否可以使用Java爬虫crawler4j暂停和恢复爬行?

javascript - Python 相当于 JavaScript 函数对象