如何在python中从csv读取编码字符串的数据帧
假设我读了一个html网站,得到了一个名字列表,比如:“阿米尔,亨利·弗里德里克” 为了获得姓名列表,我使用以下代码解码html:如何在python中从csv读取编码字符串的数据帧,python,utf-8,pandas,Python,Utf 8,Pandas,假设我读了一个html网站,得到了一个名字列表,比如:“阿米尔,亨利·弗里德里克” 为了获得姓名列表,我使用以下代码解码html: f = urllib.urlopen("http://xxx.htm") html = f.read() html=html.decode('utf8') t.feed(html) t.close() lista=t.data name=u'Amiel, Henri-Fr\xe9d\xe9ric' name=name.encode('utf8') array=[n
f = urllib.urlopen("http://xxx.htm")
html = f.read()
html=html.decode('utf8')
t.feed(html)
t.close()
lista=t.data
name=u'Amiel, Henri-Fr\xe9d\xe9ric'
name=name.encode('utf8')
array=[name]
df=pd.DataFrame({'Names':array})
df.to_csv('names')
uni=pd.read_csv('names')
uni #trying to read the csv file in a DataFrame
此时,变量lista包含一个名称列表,如:
[u'Abatantoono,Diego',
... ,
阿米尔,亨利·弗里德里克]
现在我想:
f = urllib.urlopen("http://xxx.htm")
html = f.read()
html=html.decode('utf8')
t.feed(html)
t.close()
lista=t.data
name=u'Amiel, Henri-Fr\xe9d\xe9ric'
name=name.encode('utf8')
array=[name]
df=pd.DataFrame({'Names':array})
df.to_csv('names')
uni=pd.read_csv('names')
uni #trying to read the csv file in a DataFrame
此时,我得到以下错误:
UnicodeDecodeError: 'utf8' codec can't decode byte 0xe9 in position 67: invalid continuation byte
如果我将上述代码的最后一行替换为:
print uni
我可以读取数据帧,但我认为这不是处理此问题的正确方法
我向其他用户提出了许多关于此参数的问题,但我没有解决这个问题。方法和函数都采用了
编码参数。使用它。并在内部使用unicode。如果你不这样做,尝试在你的程序中编码/解码会让你失望
输出:
很抱歉,您的代码有效,但仅当您使用“print uni”作为最后一行代码时才有效。如果只使用“uni”,则会出现错误:“UnicodeDecodeError:'utf8'编解码器无法解码第67位的字节0xe9:无效的继续字节”@fabrizio_ff--pandas
/numpy
您使用的版本是什么?@root--numpy:1.6.2//pandas:0.9.1。我试图使用你的上一个代码,但如果我只写'uni',我会得到相同的错误(它与'print uni'一起工作)。@fabrizio_ff--尝试将pandas
升级到最新版本,看看你是否仍然会得到错误。@root--将pandas升级到0.10.1。如果我使用IPython笔记本,我会得到相同的错误,而如果我使用spyder控制台,它会工作。可能是因为我用的是iPython笔记本?非常感谢。