【问题标题】:Which encoding to use while reading Excel using xlrd使用 xlrd 读取 Excel 时使用哪种编码
【发布时间】:2012-11-16 15:57:12
【问题描述】:

我正在尝试使用 xlrd 读取 Excel 文件以写入 txt 文件。一切都写得很好,除了一些行有一些西班牙字符,比如“Téd”。我可以使用 latin-1 编码对它们进行编码。但是,对于具有 'â' 和 unicode u'\u2013' 的其他行,该代码将失败。 u'\2013' 不能使用 latin-1 编码。使用 UTF-8 时,'â' 写得很好,但 'Téd' 写成 'Téd',这是不可接受的。我该如何纠正这个问题。

代码如下:

#!/usr/bin/python
import xlrd
import csv
import sys

filePath     = sys.argv[1]

with xlrd.open_workbook(filePath) as wb:
     shNames = wb.sheet_names()
     for shName in shNames:
         sh = wb.sheet_by_name(shName)
         csvFile = shName + ".csv"
         with open(csvFile, 'wb') as f:
              c = csv.writer(f)
              for row in range(sh.nrows):
                  sh_row = []
                  cell = ''
                  for item in sh.row_values(row):
                      if isinstance(item, float):
                         cell=item
                      else:
                         cell=item.encode('utf-8')
                      sh_row.append(cell)
                      cell=''
                  c.writerow(sh_row)
         print shName + ".csv File Created"

【问题讨论】:

标签: python encoding utf-8 xlrd latin1


【解决方案1】:

Python's csv module

不支持 Unicode 输入。

您在编写输入之前已正确编码 - 因此您不需要codecs。只需 open(csvFile, "wb")b 很重要)并将该对象传递给作者:

with open(csvFile, "wb") as f:
    writer = csv.writer(f)
    writer.writerow([entry.encode("utf-8") for entry in row])

或者,unicodecsv 是处理编码的csv 的直接替代品。


你得到的是é而不是é,因为you are mistaking UTF-8 encoded text for latin-1。这可能是因为您进行了两次编码,一次为.encode("utf-8"),一次为codecs.open


顺便说一句,检查xlrd 单元格类型的正确方法是使用cell.ctype == xlrd.ONE_OF_THE_TYPES

【讨论】:

  • 是的,你是对的。但是,我使用哪种编码?或者除了使用unicodecsv没有别的办法吗?
  • 从 codecs.open 中删除了编解码器并再次尝试。同样的问题!
  • @katrielalex 如何在使用您的方法时处理例如此类错误?:AttributeError: 'float' object has no attribute 'encode'
  • 您正在尝试对浮点数(即十进制数)进行编码。你必须先str它。
猜你喜欢
  • 2016-09-28
  • 2012-09-24
  • 2020-09-15
  • 2023-04-07
  • 1970-01-01
  • 2012-05-14
  • 2020-12-27
  • 1970-01-01
  • 2012-01-13
相关资源
最近更新 更多