【问题标题】:Error when Loading utf-8 file with petl module in Python在 Python 中使用 petl 模块加载 utf-8 文件时出错
【发布时间】:2016-01-21 10:18:24
【问题描述】:
    import petl as etl

    file_name = 'name of file'
    file_in_memory = etl.fromcsv(file_name, encoding='utf-8')
    print (etl.look(file_in_memory))

    Traceback (most recent call last):
      File "<interactive input>", line 1, in <module>
    UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 13: ordinal not in range(128)

该文件包含导致错误的“20 Rue d'Estrées, 75007 Paris, France”。

我可以使用 codes.open(file_name, mode='r', encoding='utf-8') 读取文件,但希望能够使用 petl 库轻松操作 csv。

有没有办法可以通过 petl.fromcsv 将其加载到内存中,同时保留字符?

【问题讨论】:

    标签: python utf-8 etl codec


    【解决方案1】:

    需要先通过chardet模块找出文件的编码。通过使用通用检测器函数,它遍历文件的内容并根据文件中的字符返回编码。

    返回带有键“encoding”的字典。

       from chardet.universaldetector import UniversalDetector
       import petl as etl
    
       detector = UniversalDetector()
       file_open = open(file_name)
       for line in file_open.readlines():
           detector.feed(line)
           if detector.done: break
       detector.close()
       file_open.close()
       file_encoding = detector.result['encoding']
    
       file_name = 'name of file'
       file_in_memory = etl.fromcsv(file_name, encoding=file_encoding)
       print (etl.look(file_in_memory))
    

    如果需要不止一次,可以将文件编码的检测放入一个函数中。

    【讨论】:

      猜你喜欢
      • 2016-01-05
      • 2018-05-17
      • 1970-01-01
      • 1970-01-01
      • 2015-06-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多