导航:首页 > 文件处理 > pythongzip压缩

pythongzip压缩

发布时间:2022-09-25 05:54:02

‘壹’ python如何读取通过gzip压缩的字符串

import osimport gzip # 那是因为你调用了read方法,而这个方法会把文件一股脑儿读取出来的# 为了便于你迭代,你可以在这里使用一个生成器def read_gz_file(path): if os.path.exists(path): with gzip.open(path, 'rt') as pf: for line in pf: yield line else: print('the path [{}] is not exist!'.format(path)) con = read_gz_file('abc.gz')if getattr(con, '__iter__', None): for line in con: print(line, end = '')

‘贰’ python压缩成tar

Python压缩文件为tar、gzip的方源码。需要应用到os、tarfile、gzip、string、shutil这几个Python类库中的方法。不同于Python Gzip压缩与解压模块,今天我们要用自己的方法实现压...

‘叁’ 为什么用Python爬知乎是乱码

这是因为知乎将网页数据做了gzip压缩。解压之后就可以了。


import sys

import urllib2

import StringIO, gzip


reload(sys)

sys.setdefaultencoding("utf-8")


def decodeGzip(data):

stream = StringIO.StringIO(data)

gziper = gzip.GzipFile(fileobj=stream)

return gziper.read()


#此处填链接,网络可能会屏蔽链接所以把链接内容省略了

url = ""


resp = urllib2.urlopen(url)


text = resp.read()


print decodeGzip(text)

‘肆’ 哪位哥哥能给个python中 tarfile,gzip,zlib 用法的代码

tarfile:

importtarfile
tar=tarfile.open("sample.tar.gz")
tar.extractall()
tar.close()

gzip

importgzip
f=gzip.open('file.txt.gz','rb')
file_content=f.read()
f.close()

zlib

#https://docs.python.org/2.7/library/zlib.html

如果解决了您的问题请采纳!
如果未解决请继续追问

‘伍’ 如何使用python爬虫jfinal

一、gzip/deflate支持

现在的网页普遍支持gzip压缩,这往往可以解决大量传输时间,以VeryCD的主页为例,未压缩版本247K,压缩了以后45K,为原来的1/5。这就意味着抓取速度会快5倍。

然而python的urllib/urllib2默认都不支持压缩,要返回压缩格式,必须在request的header里面写明’accept-
encoding’,然后读取response后更要检查header查看是否有’content-encoding’一项来判断是否需要解码,很繁琐琐
碎。如何让urllib2自动支持gzip, defalte呢?

其实可以继承BaseHanlder类,然后build_opener的方式来处理:

import urllib2
from gzip import GzipFile
from StringIO import StringIO
class ContentEncodingProcessor(urllib2.BaseHandler):
"""A handler to add gzip capabilities to urllib2 requests """

# add headers to requests
def http_request(self, req):
req.add_header("Accept-Encoding", "gzip, deflate")
return req

# decode
def http_response(self, req, resp):
old_resp = resp
# gzip
if resp.headers.get("content-encoding") == "gzip":
gz = GzipFile(
fileobj=StringIO(resp.read()),
mode="r"
)
resp = urllib2.addinfourl(gz, old_resp.headers, old_resp.url, old_resp.code)
resp.msg = old_resp.msg
# deflate
if resp.headers.get("content-encoding") == "deflate":
gz = StringIO( deflate(resp.read()) )
resp = urllib2.addinfourl(gz, old_resp.headers, old_resp.url, old_resp.code) # 'class to add info() and
resp.msg = old_resp.msg
return resp

# deflate support
import zlib
def deflate(data): # zlib only provides the zlib compress format,not the deflate format;
try: # so on top of all there's this workaround:
return zlib.decompress(data, -zlib.MAX_WBITS)
except zlib.error:
return zlib.decompress(data)

然后就简单了,

encoding_support = ContentEncodingProcessor
opener = urllib2.build_opener( encoding_support, urllib2.HTTPHandler )

#直接用opener打开网页,如果服务器支持gzip/defalte则自动解压缩
content = opener.open(url).read()

二、更方便地多线程

总结一文的确提及了一个简单的多线程模板,但是那个东东真正应用到程序里面去只会让程序变得支离破碎,不堪入目。在怎么更方便地进行多线程方面我也动了一番脑筋。先想想怎么进行多线程调用最方便呢?

1、用twisted进行异步I/O抓取

事实上更高效的抓取并非一定要用多线程,也可以使用异步I/O法:直接用twisted的getPage方法,然后分别加上异步I/O结束时的callback和errback方法即可。例如可以这么干:

from twisted.web.client import getPage
from twisted.internet import reactor

links = [ 'http://www.verycd.com/topics/%d/'%i for i in range(5420,5430) ]

def parse_page(data,url):
print len(data),url

def fetch_error(error,url):
print error.getErrorMessage(),url

# 批量抓取链接
for url in links:
getPage(url,timeout=5)
.addCallback(parse_page,url) #成功则调用parse_page方法
.addErrback(fetch_error,url) #失败则调用fetch_error方法

reactor.callLater(5, reactor.stop) #5秒钟后通知reactor结束程序
reactor.run()

twisted人如其名,写的代码实在是太扭曲了,非正常人所能接受,虽然这个简单的例子看上去还好;每次写twisted的程序整个人都扭曲了,累得不得了,文档等于没有,必须得看源码才知道怎么整,唉不提了。

如果要支持gzip/deflate,甚至做一些登陆的扩展,就得为twisted写个新的HTTPClientFactory类诸如此类,我这眉头真是大皱,遂放弃。有毅力者请自行尝试。

这篇讲怎么用twisted来进行批量网址处理的文章不错,由浅入深,深入浅出,可以一看。

2、设计一个简单的多线程抓取类

还是觉得在urllib之类python“本土”的东东里面折腾起来更舒服。试想一下,如果有个Fetcher类,你可以这么调用

f = Fetcher(threads=10) #设定下载线程数为10
for url in urls:
f.push(url) #把所有url推入下载队列
while f.taskleft(): #若还有未完成下载的线程
content = f.pop() #从下载完成队列中取出结果
do_with(content) # 处理content内容

这么个多线程调用简单明了,那么就这么设计吧,首先要有两个队列,用Queue搞定,多线程的基本架构也和“技巧总结”一文类似,push方法和
pop方法都比较好处理,都是直接用Queue的方法,taskleft则是如果有“正在运行的任务”或者”队列中的任务”则为是,也好办,于是代码如
下:

import urllib2
from threading import Thread,Lock
from Queue import Queue
import time

class Fetcher:
def __init__(self,threads):
self.opener = urllib2.build_opener(urllib2.HTTPHandler)
self.lock = Lock() #线程锁
self.q_req = Queue() #任务队列
self.q_ans = Queue() #完成队列
self.threads = threads
for i in range(threads):
t = Thread(target=self.threadget)
t.setDaemon(True)
t.start()
self.running = 0

def __del__(self): #解构时需等待两个队列完成
time.sleep(0.5)
self.q_req.join()
self.q_ans.join()

def taskleft(self):
return self.q_req.qsize()+self.q_ans.qsize()+self.running

def push(self,req):
self.q_req.put(req)

def pop(self):
return self.q_ans.get()

def threadget(self):
while True:
req = self.q_req.get()
with self.lock: #要保证该操作的原子性,进入critical area
self.running += 1
try:
ans = self.opener.open(req).read()
except Exception, what:
ans = ''
print what
self.q_ans.put((req,ans))
with self.lock:
self.running -= 1
self.q_req.task_done()
time.sleep(0.1) # don't spam

if __name__ == "__main__":
links = [ 'http://www.verycd.com/topics/%d/'%i for i in range(5420,5430) ]
f = Fetcher(threads=10)
for url in links:
f.push(url)
while f.taskleft():
url,content = f.pop()
print url,len(content)


‘陆’ python如何判断一个文件是否为gzip文件

本文实例讲述了Python实现压缩与解压gzip大文件的方法。分享给大家供大家参考,具体如下:
#encoding=utf-8
#author: walker
#date: 2015-10-26
#summary: 测试gzip压缩/解压文件
import gzip
BufSize = 1024*8
def gZipFile(src, dst):
fin = open(src, 'rb')
fout = gzip.open(dst, 'wb')
in2out(fin, fout)
def gunZipFile(gzFile, dst):
fin = gzip.open(gzFile, 'rb')
fout = open(dst, 'wb')
in2out(fin, fout)
def in2out(fin, fout):
while True:
buf = fin.read(BufSize)
if len(buf) < 1:
break
fout.write(buf)
fin.close()
fout.close()
if __name__ == '__main__':
src = r'D:\tmp\src.txt'
dst = r'D:\tmp\src.txt.gz'
ori = r'D:\tmp\ori.txt'
gZipFile(src, dst)
print('gZipFile over!')
gunZipFile(dst, ori)
print('gunZipFile over!')

也可以简单地封装成一个类:
class GZipTool:
def __init__(self, bufSize):
self.bufSize = bufSize
self.fin = None
self.fout = None
def compress(self, src, dst):
self.fin = open(src, 'rb')
self.fout = gzip.open(dst, 'wb')
self.__in2out()
def decompress(self, gzFile, dst):
self.fin = gzip.open(gzFile, 'rb')
self.fout = open(dst, 'wb')
self.__in2out()
def __in2out(self,):
while True:
buf = self.fin.read(self.bufSize)
if len(buf) < 1:
break
self.fout.write(buf)
self.fin.close()
self.fout.close()

‘柒’ 怎么样python爬虫进行此网站爬取

‘捌’ python中accept-encoding gzip deflate怎样解压

看你的请求头 GET /xxxx/xxxx/ HTTP/1.1 Accept-Encoding: gzip,deflate,sdch 是不是有这个,gzip 如果是这个就是乱码 因为是压缩的,你把这个gzip去了就行了

‘玖’ java gzip 和 python gzip 有什么区别

一个zip可以内藏多个文件 狭义的gzip仅对单个文件压缩,不能打包多个文件。 tar.gzip或tgz可以打包多个文件,属于固实压缩,压缩比较高,但随机存取单个文件的效率不如zip..

阅读全文

与pythongzip压缩相关的资料

热点内容
redhatlinux最新 浏览:177
python字典编程词汇 浏览:144
微信和服务器如何通讯 浏览:10
百家号服务器配置有什么用 浏览:598
怎么为电脑加密 浏览:58
服务器出现差错是什么意思 浏览:616
苹果app移到商店里怎么删掉 浏览:254
phpjsphtml 浏览:63
吃鸡手机国际服服务器超时怎么办 浏览:68
努比亚Z5无命令 浏览:642
展示网站云服务器 浏览:872
代码混淆器php 浏览:367
贝恩pdf 浏览:208
丙烯pdf 浏览:368
云服务器华硕 浏览:713
sublime3运行python 浏览:191
怎么把安卓视频传到苹果上面 浏览:83
手机拍鬼片用什么app 浏览:642
爬山虎app是干什么用的 浏览:507
有哪些写给程序员的歌 浏览:51