【问题标题】:Reading utf-8 characters from a gzip file in python从 python 中的 gzip 文件中读取 utf-8 字符
【发布时间】:2010-12-25 09:53:08
【问题描述】:

我正在尝试在 python 中读取 gunzipped 文件 (.gz),但遇到了一些问题。

我使用 gzip 模块来读取它,但文件被编码为 utf-8 文本文件,因此最终它读取了无效字符并崩溃。

有人知道如何读取编码为 utf-8 文件的 gzip 文件吗?我知道有一个编解码器模块可以提供帮助,但我不明白如何使用它。

谢谢!

import string
import gzip
import codecs

f = gzip.open('file.gz','r')

engines = {}
line = f.readline()
while line:
    parsed = string.split(line, u'\u0001')

    #do some things...

    line = f.readline()
for en in engines:
  print(en)

【问题讨论】:

  • 你能发布你到目前为止的代码吗?
  • 你能把 utf-8 文件转换成 ascii 然后再解压吗?嗯....
  • 如果您遇到 UnicodeDecodeError,请参阅此相关帖子,其中显示了 open('errors') 参数的使用,并在使用 ISO-8859-1 (latin-1) 时提出了警告编码:stackoverflow.com/questions/35028683/…

标签: python file-io utf-8 gzip


【解决方案1】:

从 Python 3.3 开始,这是可能的:

import gzip
gzip.open('file.gz', 'rt', encoding='utf-8')

请注意,gzip.open() 要求您明确指定文本模式 ('t')。

【讨论】:

    【解决方案2】:

    我不明白为什么这会这么难。

    你到底在做什么?请解释“最终它读取一个无效字符”。

    应该很简单:

    import gzip
    fp = gzip.open('foo.gz')
    contents = fp.read() # contents now has the uncompressed bytes of foo.gz
    fp.close()
    u_str = contents.decode('utf-8') # u_str is now a unicode string
    

    已编辑

    此答案适用于Python3 中的Python2,请参阅@SeppoEnarvi 在https://stackoverflow.com/a/19794943/610569 的答案(它对gzip.open 使用rt 模式。

    【讨论】:

    • +1 ... 这是迄今为止 3 个答案中最清晰、最简单的答案。
    • 不一定是最简单的,因为你必须解码你阅读的每一行。在 getreader 实现中,这是自动发生的,所以每一行都是 unicode
    • 虽然这是一个不错的解决方案,但我感觉这个解决方案无法很好地适应大文件。
    • 没错。我们希望库能够正确解释这一点,而不是在被要求将整个内容读入字符串之后由我们正确解释。
    【解决方案3】:

    也许

    import codecs
    zf = gzip.open(fname, 'rb')
    reader = codecs.getreader("utf-8")
    contents = reader( zf )
    for line in contents:
        pass
    

    【讨论】:

    • 单行:for line in codecs.getreader('utf-8')(gzip.open(fname), errors='replace') 这也增加了对错误处理的控制
    【解决方案4】:

    以上产生了大量的解码错误。我用这个:

    for line in io.TextIOWrapper(io.BufferedReader(gzip.open(filePath)), encoding='utf8', errors='ignore'):
        ...
    

    【讨论】:

      【解决方案5】:

      pythonic 形式(2.5 或更高版本)

      from __future__ import with_statement # for 2.5, does nothing in 2.6
      from gzip import open as gzopen
      
      with gzopen('foo.gz') as gzfile:
          for line in gzfile:
            print line.decode('utf-8')
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-07-25
        • 2021-06-24
        • 2021-07-19
        • 2015-07-26
        相关资源
        最近更新 更多