我需要一些列表编码方面的帮助。对不起,我是python的新手。 首先,我使用的是Python 2.7.3
我有两个列表(entidad& valores),我需要对它们进行编码或其中一些。
我的代码:
import urllib
from bs4 import BeautifulSoup
import csv
sock = urllib.urlopen("http://www.fatm.com.es/Datos_Equipo.asp?Cod=01HU0010")
htmlSource = sock.read()
sock.close()
soup = BeautifulSoup(htmlSource)
form = soup.find("form", {'id': "FORM1"})
table = form.find("table")
entidad = [item.text.strip() for item in table.find_all('td')]
valores = [item.get('value') for item in form.find_all('input')]
valores.remove('Imprimir')
valores.remove('Cerrar')
header = entidad
values = valores
print values
out = open('tomate.csv', 'w')
w = csv.writer(out)
w.writerow(header)
w.writerow(values)
out.close()
日志: UnicodeEncodeError:'ascii'编解码器无法编码字符
任何想法?在此先感谢!!
答案 0 :(得分:2)
您应该手动将数据编码为utf-8,csv.writer没有为您执行此操作:
w.writerow([s.encode("utf-8") for s in header])
w.writerow([s.encode("utf-8") for s in values])
#w.writerow(header)
#w.writerow(values)
答案 1 :(得分:0)
这似乎与此处UnicodeEncodeError in csv writer in Python
中发现的问题类型相同Python中csv writer中的UnicodeEncodeError 今天我写的是 在一些处理之后生成csv文件的程序。但我得到了 在尝试某些测试数据时出现以下错误:
writer.writerow(csv_li)UnicodeEncodeError:'ascii'编解码器无法编码 字符u'\ xbf'位于第5位:序数不在范围内(128)
我在Python中查看了csv模块的文档并找到了一个 类名为UnicodeWriter。所以我将代码更改为
writer = UnicodeWriter(open(“filename.csv”,“wb”))
然后我试着再次运行它。它摆脱了以前 UnicodeEncodeError但又遇到了另一个错误。
self.writer.writerow([s.encode(“utf-8”)for s in row])AttributeError: 'int'对象没有属性'encode'
因此,在编写列表之前,我必须将每个值都更改为字符串。
row = [str(item)for item in row]
我认为这一行可以在作者的函数中添加 UnicodeWriter类。