无法在python中将unicode转换为字符串获取错误
我正在将excel文件中的一列读取到一个列表中,如下所示:无法在python中将unicode转换为字符串获取错误,python,excel,string,unicode,unicode-string,Python,Excel,String,Unicode,Unicode String,我正在将excel文件中的一列读取到一个列表中,如下所示: import xlrd import openpyxl book = xlrd.open_workbook("English corpus.xlsx") sheet = book.sheet_by_index(0) data=[] for row_index in xrange(1, sheet.nrows): # skip heading row timestamp, text, header, transporter,
import xlrd
import openpyxl
book = xlrd.open_workbook("English corpus.xlsx")
sheet = book.sheet_by_index(0)
data=[]
for row_index in xrange(1, sheet.nrows): # skip heading row
timestamp, text, header, transporter, device_type = sheet.row_values(row_index, end_colx=5)
print (text)
data.append(text)
但对于数据列表中的元素,其类型为“unicode”。我尝试执行以下操作以将它们转换为字符串:
[x.encode('UTF8') for x in data]
但它给了我以下错误:
AttributeError: 'int' object has no attribute 'encode'
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 176: ordinal not in range(128)
然后我试着做了以下几件事:
[str(x).encode('UTF8') for x in data]
这给了我以下错误:
AttributeError: 'int' object has no attribute 'encode'
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 176: ordinal not in range(128)
或:
如果您能告诉我如何从excel列中读取到列表中,而不是作为unicode元素,而是普通字符串。谢谢最后一个错误来自str(x)
;如果使用[unicode(x).encode('UTF8')表示数据中的x]
,则可以避免该错误。属性的类型似乎是int
,而不是unicode
。unicode
是字符串。除非你需要ascii码,否则你可能根本不需要转换它。但是我希望这样可以删除错误,但是列表元素仍然只保留unicode类型,而不是字符串类型。data=[unicode(x)。encode('UTF8')for x in data]
将用新列表替换旧列表。