在Python中使用zlib模块进行数据压缩的教程
Python标准模块中,有多个模块用于数据的压缩与解压缩,如zipfile,gzip, bz2等等。上次介绍了zipfile模块,今天就来讲讲zlib模块。
zlib.compress(string[, level])
zlib.decompress(string[, wbits[, bufsize]])
zlib.compress用于压缩流数据。参数string指定了要压缩的数据流,参数level指定了压缩的级别,它的取值范围是1到9。压缩速度与压缩率成反比,1表示压缩速度最快,而压缩率最低,而9则表示压缩速度最慢但压缩率最高。zlib.decompress用于解压数据。参数string指定了需要解压的数据,wbits和bufsize分别用于设置系统缓冲区大小(window buffer )与输出缓冲区大小(output buffer)。下面用一个例子来演示如何使用这两个方法:
#coding=gbk import zlib, urllib fp = urllib.urlopen('http://localhost/default.html') str = fp.read() fp.close() #---- 压缩数据流。 str1 = zlib.compress(str, zlib.Z_BEST_COMPRESSION) str2 = zlib.decompress(str1) print len(str) print len(str1) print len(str2) # ---- 结果 #5783 #1531 #5783
我们也可以使用Compress/Decompress对象来对数据进行压缩/解压缩。zlib.compressobj([level]) 与zlib.decompress(string[, wbits[, bufsize]]) 分别创建Compress/Decompress缩对象。通过对象对数据进行压缩和解压缩的使用方式与上面介绍的zlib.compress,zlib.decompress非常类似。但两者对数据的压缩还是有区别的,这主要体现在对大量数据进行操作的情况下。假如现在要压缩一个非常大的数据文件(上百M),如果使用zlib.compress来压缩的话,必须先一次性将文件里的数据读到内存里,然后将数据进行压缩。这样势必会战用太多的内存。如果使用对象来进行压缩,那么没有必要一次性读取文件的所有数据,可以先读一部分数据到内存里进行压缩,压缩完后写入文件,然后再读其他部分的数据压缩,如此循环重复,只到压缩完整个文件。下面一个例子来演示这之间的区别:
#coding=gbk import zlib, urllib fp = urllib.urlopen('http://localhost/default.html') # 访问的到的网址。 data = fp.read() fp.close() #---- 压缩数据流 str1 = zlib.compress(data, zlib.Z_BEST_COMPRESSION) str2 = zlib.decompress(str1) print '原始数据长度:', len(data) print '-' * 30 print 'zlib.compress压缩后:', len(str1) print 'zlib.decompress解压后:', len(str2) print '-' * 30 #---- 使用Compress, Decompress对象对数据流进行压缩/解压缩 com_obj = zlib.compressobj(zlib.Z_BEST_COMPRESSION) decom_obj = zlib.decompressobj() str_obj = com_obj.compress(data) str_obj += com_obj.flush() print 'Compress.compress压缩后:', len(str_obj) str_obj1 = decom_obj.decompress(str_obj) str_obj1 += decom_obj.flush() print 'Decompress.decompress解压后:', len(str_obj1) print '-' * 30 #---- 使用Compress, Decompress对象,对数据进行分块压缩/解压缩。 com_obj1 = zlib.compressobj(zlib.Z_BEST_COMPRESSION) decom_obj1 = zlib.decompressobj() chunk_size = 30; #原始数据分块 str_chunks = [data[i * chunk_size:(i + 1) * chunk_size] / for i in range((len(data) + chunk_size) / chunk_size)] str_obj2 = '' for chunk in str_chunks: str_obj2 += com_obj1.compress(chunk) str_obj2 += com_obj1.flush() print '分块压缩后:', len(str_obj2) #压缩数据分块解压 str_chunks = [str_obj2[i * chunk_size:(i + 1) * chunk_size] / for i in range((len(str_obj2) + chunk_size) / chunk_size)] str_obj2 = '' for chunk in str_chunks: str_obj2 += decom_obj1.decompress(chunk) str_obj2 += decom_obj1.flush() print '分块解压后:', len(str_obj2) # ---- 结果 ------------------------ 原始数据长度: 5783 ------------------------------ zlib.compress压缩后: 1531 zlib.decompress解压后: 5783 ------------------------------ Compress.compress压缩后: 1531 Decompress.decompress解压后: 5783 ------------------------------ 分块压缩后: 1531 分块解压后: 5783
Python手册对zlib模块的介绍比较详细,更具体的应用,可以参考Python手册。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PS "Loading" problems are caused by resource access or processing problems: hard disk reading speed is slow or bad: Use CrystalDiskInfo to check the hard disk health and replace the problematic hard disk. Insufficient memory: Upgrade memory to meet PS's needs for high-resolution images and complex layer processing. Graphics card drivers are outdated or corrupted: Update the drivers to optimize communication between the PS and the graphics card. File paths are too long or file names have special characters: use short paths and avoid special characters. PS's own problem: Reinstall or repair the PS installer.

A PS stuck on "Loading" when booting can be caused by various reasons: Disable corrupt or conflicting plugins. Delete or rename a corrupted configuration file. Close unnecessary programs or upgrade memory to avoid insufficient memory. Upgrade to a solid-state drive to speed up hard drive reading. Reinstalling PS to repair corrupt system files or installation package issues. View error information during the startup process of error log analysis.

"Loading" stuttering occurs when opening a file on PS. The reasons may include: too large or corrupted file, insufficient memory, slow hard disk speed, graphics card driver problems, PS version or plug-in conflicts. The solutions are: check file size and integrity, increase memory, upgrade hard disk, update graphics card driver, uninstall or disable suspicious plug-ins, and reinstall PS. This problem can be effectively solved by gradually checking and making good use of PS performance settings and developing good file management habits.

The article introduces the operation of MySQL database. First, you need to install a MySQL client, such as MySQLWorkbench or command line client. 1. Use the mysql-uroot-p command to connect to the server and log in with the root account password; 2. Use CREATEDATABASE to create a database, and USE select a database; 3. Use CREATETABLE to create a table, define fields and data types; 4. Use INSERTINTO to insert data, query data, update data by UPDATE, and delete data by DELETE. Only by mastering these steps, learning to deal with common problems and optimizing database performance can you use MySQL efficiently.

The key to feather control is to understand its gradual nature. PS itself does not provide the option to directly control the gradient curve, but you can flexibly adjust the radius and gradient softness by multiple feathering, matching masks, and fine selections to achieve a natural transition effect.

MySQL has a free community version and a paid enterprise version. The community version can be used and modified for free, but the support is limited and is suitable for applications with low stability requirements and strong technical capabilities. The Enterprise Edition provides comprehensive commercial support for applications that require a stable, reliable, high-performance database and willing to pay for support. Factors considered when choosing a version include application criticality, budgeting, and technical skills. There is no perfect option, only the most suitable option, and you need to choose carefully according to the specific situation.

MySQL performance optimization needs to start from three aspects: installation configuration, indexing and query optimization, monitoring and tuning. 1. After installation, you need to adjust the my.cnf file according to the server configuration, such as the innodb_buffer_pool_size parameter, and close query_cache_size; 2. Create a suitable index to avoid excessive indexes, and optimize query statements, such as using the EXPLAIN command to analyze the execution plan; 3. Use MySQL's own monitoring tool (SHOWPROCESSLIST, SHOWSTATUS) to monitor the database health, and regularly back up and organize the database. Only by continuously optimizing these steps can the performance of MySQL database be improved.

The loading interface of PS card may be caused by the software itself (file corruption or plug-in conflict), system environment (due driver or system files corruption), or hardware (hard disk corruption or memory stick failure). First check whether the computer resources are sufficient, close the background program and release memory and CPU resources. Fix PS installation or check for compatibility issues for plug-ins. Update or fallback to the PS version. Check the graphics card driver and update it, and run the system file check. If you troubleshoot the above problems, you can try hard disk detection and memory testing.
