2014-06-24 2 views
0

xlrd을 사용하여 Excel에서 일부 데이터를 읽으려고합니다. 시그마, 파이 등의 특수 문자가 포함 된 셀이 있습니다. 하지만 xlrd은 나를 UnicodeEncodeError라고합니다.Python XLRD 모듈이 일부 ASCII 문자에 대해 ValueError를 제공합니다.

이 내 엑셀 파일입니다

enter image description here

이 내가 사용하는 코드입니다 :

import xlrd 
if __name__ == '__main__': 
    wb = xlrd.open_workbook('test.xlsx') 
    s = wb.sheet_by_name('test') 
    for row in range(1, s.nrows): 
     values = {} 
     for column in range(s.ncols): 
      values.update({s.cell(0, column).value: str(s.cell(row, column).value)})  
      print values 

가 그리고 이것은 출력 : 어떻게해야합니까

{u'formula': 'a + b * 15', u'name': 'test1'} 
Traceback (most recent call last): 
    File ".\testXLRD.py", line 21, in <module> 
    values.update({s.cell(0, column).value: str(s.cell(row, column).value)}) 
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2211' in position 0: ordinal not in range(128) 

??

+0

내 추측 : 값을'str()'으로 캐스팅하고 있습니다. 파이썬은 ascii (기본값)를 사용하여 문자열을 디코딩합니다. 's.cell (row, column) .value'의 반환 값은 무엇입니까 ?? – Mathias

+0

Sebastien의 답변에 남긴 의견을 확인하십시오. –

답변

0

Mathias가 말했듯이 str() 유니 캐스트 문자열 u'\u2211'을 ASCII 형식으로 디코딩하려고 시도했기 때문에 캐스트가 실패했습니다. 반면에 'utf-8'은 사용해야합니다.

values.update({s.cell(0, column).value: unicode(s.cell(row, column).value)}) 

당신이 정말로 문자열을 원하는 경우에, 그리고 유니 코드 :

s.cell(row, column) 이후 반환 a float, an int or some unicode string, 당신은 당신이 그것을 조작하는 동안 형식을 변경 또는 유니 코드의 모든 변환하지 않는 중 더 나은 거라고 ,이 작동합니다 :

values.update({s.cell(0, column).value: unicode(s.cell(row, column).value).encode('utf-8')}) 
+0

이것은 두 번째 행의 출력입니다.'{u'formula ': u'\ u2211 (ai) ', u'name': u'test2 '}'. 나는 그것을 원하지 않는다. 나는 실제 "시그마"특성을 원해. –

+0

'u '\ u2211 (ai)''는 정확히 원하는 문자이며 유니 코드로 저장됩니다. 'print u'\ u2211 (ai) ''를 예로 들어보십시오. 당신의 dict에'string'을 저장하고 싶다면'unicode'가 아니라 두번째 형식을 사용할 수 있습니다. 보통 유니 코드로 작업하고 출력을 위해 변환하는 것을 선호합니다. –

+0

두 번째 해결책은 다음과 같습니다.'{u'formula ':'\ xe2 \ x88 \ x91 (ai) ', u'name': 'test2'}'. 나는 실제로 시그마 기호를 원한다. –