【问题标题】:Ascii Code error while converting from xlsx to csv从 xlsx 转换为 csv 时出现 Ascii 代码错误
【发布时间】:2014-08-20 07:30:00
【问题描述】:

我已经提到了一些与 unicode 错误相关的帖子,但我的问题没有得到任何解决方案。我正在将 xlsx 转换为 csv 来自 6 张工作簿。 使用以下代码

def csv_from_excel(file_loc):

    #file_acess check
    print os.access(file_loc, os.R_OK)
    wb = xlrd.open_workbook(file_loc)
    print wb.nsheets

    sheet_names = wb.sheet_names()
    print sheet_names
    counter = 0

    while counter < wb.nsheets:
        try:
            sh = wb.sheet_by_name(sheet_names[counter])
            file_name = str(sheet_names[counter]) + '.csv'
            print file_name
            fh = open(file_name, 'wb')
            wr = csv.writer(fh, quoting=csv.QUOTE_ALL)

            for rownum in xrange(sh.nrows):
                wr.writerow(sh.row_values(rownum))

        except Exception as e:
            print str(e)

        finally:
            fh.close()
            counter += 1

我在第 4 页出现错误

'ascii' codec can't encode character u'\u2018' in position 0: ordinal not in range(128)" 

但位置 0 是空白的,并且它已转换为 csv 直到第 33 行。

我无法弄清楚。 CSV 是读取内容并放入我的数据结构的简单方法。

【问题讨论】:

    标签: python csv unicode ascii codec


    【解决方案1】:

    您需要手动将 Unicode 值编码为字节;对于 CSV,通常 UTF-8 就可以了:

    for rownum in xrange(sh.nrows):
        wr.writerow([unicode(c).encode('utf8') for c in sh.row_values(rownum)])
    

    这里我将unicode() 用于非文本的列数据。

    您遇到的字符是U+2018 LEFT SINGLE QUOTATION MARK,它只是' 单引号的一种奇特形式。办公软件(电子表格、文字处理器等)通常会用“花式”版本自动替换单引号和双引号。您也可以替换 ASCII 等价物。您可以使用Unidecode package

    from unidecode import unidecode
    
    for rownum in xrange(sh.nrows):
        wr.writerow([unidecode(unicode(c)) for c in sh.row_values(rownum)])
    

    当非 ASCII 代码点仅用于引号和破折号以及其他标点符号时使用此选项。

    【讨论】:

    • 非常感谢@martijn-pieters。第一个示例和直接编码为 utf-8 似乎有效。使用 Unidecode 是万无一失的方法吗?为什么会发生这种情况。我们不能单独声明一个完整文件的编码标准吗?
    • @nij_wiz:Python 2 中的 CSV 模块无法处理 Unicode;它的编写早于 Python 中的 Unicode 支持。这已在 Python 3 中修复。Unidecode 是一种实用的方法,可通过将任何非 ASCII 文本替换为 ASCII 等价物如果可用来确保数据仅使用 ASCII 代码点。这是否万无一失,取决于您的确切数据。
    • @martijin : 是的.. 我使用的是 2.7 所以这个问题.. 我使用了很多第三方库,这些库尚未移植到 python 3. 我使用 3.4 进行网络和其他工作.感谢您的宝贵意见
    猜你喜欢
    • 2015-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-03
    • 2022-11-07
    • 2013-03-06
    • 2020-09-14
    相关资源
    最近更新 更多