python - 使用 xlrd 读取 Excel 时使用哪种编码

标签 python encoding utf-8 xlrd latin1

我正在尝试使用 xlrd 读取 Excel 文件以写入 txt 文件。除了某些行包含一些西类牙字符(例如“Téd”)之外,所有内容都写得很好。我可以使用 latin-1 编码对它们进行编码。然而,对于其他具有 unicode u'\u2013' 的 'â' 的行,代码会失败。 u'\2013' 无法使用 latin-1 进行编码。使用 UTF-8 时,'â' 写得很好,但 'Téd' 写为 'Téd',这是 Not Acceptable 。我该如何纠正这个问题。

代码如下:

#!/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's csv module

doesn’t support Unicode input.

您在写入之前已正确编码输入 - 因此您不需要编解码器。只需 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

关于python - 使用 xlrd 读取 Excel 时使用哪种编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13420049/

相关文章:

php - 需要UTF-8 php文件

r - R Studio 中的汉字编码

c++ - 使用 Sqlite3 C++ 和 VisualStudio2010 插入期间的编码问题

http - 解码 URL 中的变音符号(或复合编码与预组合编码)

python - python中的文本或数据库,速度和资源消耗

python - Ruby GTK 失败无显示(Python 还可以)

python - 从 web.py url 访问文件

php - Python + Django 或 PHP + Zend Framework

java - 设置默认 Java 字符编码

java - OpenCSV CsvToBean : First column not read for UTF-8 Without BOM