Python中使用bz2模块进行字符串的压缩与解压缩
发布时间:2023-12-19 03:05:36
Python中使用bz2模块进行字符串的压缩和解压缩,可以通过以下代码实现:
import bz2
def compress_string(string):
# 将字符串压缩为字节流
compressed_data = bz2.compress(string.encode())
return compressed_data
def decompress_string(compressed_data):
# 将字节流解压缩为字符串
decompressed_string = bz2.decompress(compressed_data).decode()
return decompressed_string
# 示例使用
string = "Hello, World! This is a test string for compression."
# 压缩字符串
compressed_data = compress_string(string)
print("Compressed data:", compressed_data)
# 解压缩字符串
decompressed_string = decompress_string(compressed_data)
print("Decompressed string:", decompressed_string)
输出结果:
Compressed data: b'BZh91AY&SY\x82\x89\x15\x00\x00\x81\x00!\x9ah3M\x13<]\xc9\x14\xe1BA\x06\xbe\x084' Decompressed string: Hello, World! This is a test string for compression.
以上代码中,compress_string函数将输入的字符串压缩为字节流,并返回压缩后的数据。decompress_string函数将输入的字节流解压缩为字符串,并返回解压缩后的结果。
在示例中,我们首先定义了一个测试用的字符串string,然后将其压缩为字节流并打印出来。接下来,将压缩后的字节流解压缩为字符串,并打印出解压缩后的结果。
需要注意的是,bz2模块由Python提供的标准库,因此在使用之前无需额外安装。同时,compress函数和decompress函数分别用于压缩和解压缩操作。
