Python 3.6 在python3中,如何将二进制1和0存储为位而不是字节?
我正在尝试使用python中的huffman编码进行文件压缩,并且已经成功地为文件中的每个唯一字符构建了代码。现在,当我用这个代码编码原始文件时,它会生成一个1和0的序列。但是,每个字符都有一个字节,我想知道如何存储代码,以便在python3中将每个1和0存储为位,而不是字节,这将实际减少文件大小Python 3.6 在python3中,如何将二进制1和0存储为位而不是字节?,python-3.6,huffman-code,Python 3.6,Huffman Code,我正在尝试使用python中的huffman编码进行文件压缩,并且已经成功地为文件中的每个唯一字符构建了代码。现在,当我用这个代码编码原始文件时,它会生成一个1和0的序列。但是,每个字符都有一个字节,我想知道如何存储代码,以便在python3中将每个1和0存储为位,而不是字节,这将实际减少文件大小 #This is the file i redirect my output to sys.stdout=open("./input2.txt","w") #Tree for storing the
#This is the file i redirect my output to
sys.stdout=open("./input2.txt","w")
#Tree for storing the code
class Tree:
__slots__=["left","right","val","c"]
def __init__(self,val,c):
self.val=val
self.c=c
self.left=self.right=None
def value(self):
return (self.val,self.c)
#Tree is a list of tree nodes. Initially it is a list where each
#character is a seperate tree.
def construct(tree):
while(len(tree)>1):
left=_heapq.heappop(tree)
right=_heapq.heappop(tree)
root=(left[0]+right[0],left[1]+right[1],Tree(left[0]+right[0],left[1]+right[1]))
root[2].left=left[2]
root[2].right=right[2]
_heapq.heappush(tree,root)
return tree
#This function generates the code for the characters in the tree which
#is the 'root' argument and 'code' is an empty String
#'codes' is the map for mapping character with its code
def Print(root,code,codes):
if(root.left==None and root.right==None):
codes[root.c]=code
return
Print(root.left,code+'0',codes)
Print(root.right,code+'1',codes)
#This function encodes the 'compressed' string with the 'codes' map
def encode(compressed,codes):
document=''.join(list(map(lambda x:codes[x],compressed)))
return document
我的输出如下:
1101110011101110011101111110011101110011101010000101101101101111010100111110111001101110100111110111011110111100011101111010111111111111010101111111111111010101110111111111111111111101110111111111011110110110111010001110110110111111111110101101011010
问题是1和0中的每一个都存储为字符,每个字符的长度为4个字节,我希望它们存储为位您没有将其保存到文件中的代码,因此我无法确定。不过我可以在这里猜一猜 您可能忘记了将1和0代码打包在一起。在存储到文件之前,您可能需要使用
字节
或字节
类型(有关文档,请参阅),并使用位运算符(有关信息,请参阅)将8个代码移位并打包到每个字节
请注意将代码打包到字节中的位顺序
我没有使用这些,但您可能会发现pack
例程很有用。有关信息,请参见。您好,您能在问题中包含代码的相关部分吗?我通过将sys.stdout分配到输出文件来保存它。感谢您的帮助!