【问题标题】:urlopen trouble while trying to download a gzip file尝试下载 gzip 文件时出现 urlopen 问题
【发布时间】:2013-08-11 08:49:52
【问题描述】:

我将使用维基词典转储来进行 POS 标记。不知何故下载时卡住了。这是我的代码:

import nltk
from urllib import urlopen
from collections import Counter
import gzip

url = 'http://dumps.wikimedia.org/enwiktionary/latest/enwiktionary-latest-all-titles-in-ns0.gz'
fStream = gzip.open(urlopen(url).read(), 'rb')
dictFile = fStream.read()
fStream.close()

text = nltk.Text(word.lower() for word in dictFile())
tokens = nltk.word_tokenize(text)

这是我得到的错误:

Traceback (most recent call last):
File "~/dir1/dir1/wikt.py", line 15, in <module>
fStream = gzip.open(urlopen(url).read(), 'rb')
File "/usr/lib/python2.7/gzip.py", line 34, in open
return GzipFile(filename, mode, compresslevel)
File "/usr/lib/python2.7/gzip.py", line 89, in __init__
fileobj = self.myfileobj = __builtin__.open(filename, mode or 'rb')
TypeError: file() argument 1 must be encoded string without NULL bytes, not str
Process finished with exit code 1

【问题讨论】:

    标签: python gzip urllib urlopen


    【解决方案1】:

    您正在将下载的数据传递给gzip.open(),它需要传递一个文件名。

    然后代码尝试打开以 gzip 压缩数据命名的文件名,但失败了。

    要么将 URL 数据保存到文件中,然后在 上使用 gzip.open(),要么使用 zlib 模块解压缩压缩后的数据。 “保存”数据可以像使用StringIO.StringIO() 内存文件对象一样简单:

    from StringIO import StringIO
    from urllib import urlopen
    import gzip
    
    
    url = 'http://dumps.wikimedia.org/enwiktionary/latest/enwiktionary-latest-all-titles-in-ns0.gz'
    inmemory = StringIO(urlopen(url).read())
    fStream = gzip.GzipFile(fileobj=inmemory, mode='rb')
    

    【讨论】:

    • 啊,StringIO,我多么爱你。
    • @J.F.Sebastian: GzipFile 期望能够在文件中查找,urlopen() 文件对象不支持查找。
    • @MartijnPieters:这是一个在 Python 3.2 中修复并向后移植到 Python 2 的错误
    • @J.F.Sebastian:你的意思是this issue?我没有看到反向移植,但我可能遗漏了一些东西。
    猜你喜欢
    • 1970-01-01
    • 2015-09-01
    • 2011-07-12
    • 2016-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多