尝试下载gzip文件时遇到麻烦

1 python gzip urllib urlopen

我将使用wikitionary转储来进行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)
Run Code Online (Sandbox Code Playgroud)

这是我得到的错误:

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
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 6

您正在将下载的数据传递给gzip.open(),期望传递文件名.

然后代码尝试打开由gzip压缩数据命名的文件名,然后失败.

无论是URL数据保存到一个文件,然后使用gzip.open()使用,或解压缩的gzip压缩的数据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')
Run Code Online (Sandbox Code Playgroud)