我正在尝试将一个数据集加载到pandas中,但无法通过步骤1。我是新来的,请原谅,如果这是显而易见的,我已经搜索了以前的主题,没有找到答案。数据大多是汉字,这可能是问题所在。在
.csv非常大,可以在这里找到:http://weiboscope.jmsc.hku.hk/datazip/ 我在试第一周。在
在下面的代码中,我确定了我尝试的3种解码类型,包括尝试查看使用了什么编码
import pandas
import chardet
import os
#this is what I tried to start
data = pandas.read_csv('week1.csv', encoding="utf-8")
#spits out error: UnicodeDecodeError: 'utf-8' codec can't decode byte 0x9a in position 69: invalid start byte
#Code to check encoding -- this spits out ascii
bytes = min(32, os.path.getsize('week1.csv'))
raw = open('week1.csv', 'rb').read(bytes)
chardet.detect(raw)
#so i tried this! it also fails, which isn't that surprising since i don't know how you'd do chinese chars in ascii anyway
data = pandas.read_csv('week1.csv', encoding="ascii")
#spits out error: UnicodeDecodeError: 'ascii' codec can't decode byte 0xe6 in position 0: ordinal not in range(128)
#for god knows what reason this allows me to load data into pandas, but definitely not correct encoding because when I print out first 5 lines its gibberish instead of Chinese chars
data = pandas.read_csv('week1.csv', encoding="latin1")
任何帮助将不胜感激!在
编辑:@Kristof提供的答案确实有效,正如我的一位同事昨天编制的程序一样:
^{pr2}$我还想为未来的搜索者补充这是2012年的微博开放数据。在
输入文件似乎有点不对劲。始终存在编码错误。在
你可以做的一件事是将CSV文件作为二进制文件读取,解码二进制字符串并替换错误的字符。在
示例(source表示块读取代码):
相关问题 更多 >
编程相关推荐