- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个程序可以计算大量数据并将其写入文件。我的数据只是一堆 0-16 的数字(17 个不同的值),我计算了每个数字在数据中出现的频率。我需要使用尽可能少的磁盘空间和尽可能少的 RAM,所以我用纯 python 编写了一个小的 Huffman 编码/解码模块,它一次在内存中写入/读取带有尽可能少的编码符号的压缩数据。有没有python自带的模块可以做类似的事情?下面是代码,其中包含一些如何使用它的示例(警告代码有点长,注释得体):
def makeTree(data):
"""data is a list of tuples, whos first entry is a priority/frequency
number, and whos second entry is tuple containing the data to
be encoded. The tree uses an internal tag system to tell where the
branch ends. (End nodes are terminated with a False)"""
def tag(data):
taggedData = []
for priority, datum in data:
#all of the initial data is an end branch
taggedData += [(priority, (datum, False))]
return taggedData
#get the tagged data into decending order of priority/frequency
tree = sorted(tag(data), reverse=True)
while len(tree)>1:
#get the two lowest priority branches
bottomR, bottomL = tree.pop(), tree.pop()
#and stick them together into a new branch with combined priority
new_elem = bottomR[0]+bottomL[0], ((bottomL, bottomR), True)
#then add them back to the list of branches and sort
tree += [new_elem]
tree.sort(reverse=True)
return tree[0]
def makeTable(tree, code=""):
"""Takes a tree such as generated by makeTree and returns a dictionary
of code:value pairs."""
#if this is an end branch, return code:value pair
if tree[1][1]==False:
return {code:tree[1][0]}
#otherwise find the tables for the left and right branches
#add them to the main table, and return
table = {}
table.update(makeTable(tree[1][0][0], code+'0')) #left
table.update(makeTable(tree[1][0][1], code+'1')) #right
return table
class Decoder:
"""this class creates a Decoder object which is used to decode a compressed
file using the appropriate decoding table (duh). It used to be a function,
but it was buggy and would also be ugly if I left it a function. (this
class was written After the Encdoer class.)
"""
def __init__(self, fname, table):
self.file = open(fname)
self.table = table
self.byte = None
self.bit = 7
self.newByte = True
def decode(self, size=1):
"""Decodes and yields size number of symbols from the file.
Size defaults to 1"""
#a counter for how many symbols were read
read = 0
code = ''
while read<size:
if self.newByte:
self.byte = ord(self.file.read(1))
for n in xrange(self.bit, -1, -1):
code += str((self.byte & 1<<n) >> n)
self.byte &= (1<<n)-1
if code in self.table:
yield self.table[code]
read += 1
code = ''
if read==size:
self.bit = n-1
self.newByte = False
raise StopIteration
self.bit = 7
self.newByte = True
def close(self):
self.file.close()
class Encoder:
"""This class creates an encoder object, which is used to write encoded data
to a file. It was initially going to be a function, but I couldn't
accomplish that without code getting really ugly. :p """
def __init__(self, fname, table):
self.file = open(fname, 'w')
self.table = table
self.code = ''
def encode(self, datum):
"""Attempts to write encoded datum to file. If their isn't enough
code to write a whole number amount of bytes, then the code is saved up
until there is."""
self.code += self.table[datum]
if len(self.code)%8==0:
self.__write_code_chunk()
return
def end_encode(self):
"""Writes any remaining code to the file, appending the code with
trailing zeros to fit within a byte, then closes the file."""
#if the length of the code remaining isn't a multiple of 8 bits
if len(self.code)%8:
#then add zeros to the end so that it is
self.code += "0"*(8 - len(self.code)%8)
self.__write_code_chunk()
self.file.close()
return
def __write_code_chunk(self):
bytes = len(self.code)/8
#for every byte (or every 8 bits)...
for _ in xrange(bytes):
#turn those bits into an number using int with base 2,
#then turn the number into an ascii character,
#and finally write the data to the file.
self.file.write(chr(int(self.code[:8], 2)))
#then get rid of the 8 bits just read
self.code = self.code[8:]
#make sure there is no code left over
assert self.code==''
return
if __name__=="__main__":
import random
mandelbrotData = [
(0.10776733333333334, 0),
(0.24859, 1),
(0.12407666666666667, 2),
(0.07718866666666667, 3),
(0.04594733333333333, 4),
(0.03356, 5),
(0.023286666666666664, 6),
(0.018338, 7),
(0.014030666666666667, 8),
(0.011918, 9),
(0.009500666666666668, 10),
(0.008396666666666667, 11),
(0.006936, 12),
(0.006365999999999999, 13),
(0.005466, 14),
(0.0048920000000000005, 15),
(0.2537393333333333, 16)]
decode_table = makeTable(makeTree(mandelbrotData))
encode_table = {val:key for key, val in decode_table.iteritems()}
approx_data = sum([[val]*int(round(freq*10**3/2)) for freq, val in mandelbrotData], [])
random.shuffle(approx_data)
testname = 'hufftest'
encoder = Encoder(testname, encode_table)
for val in approx_data:
encoder.encode(val)
encoder.end_encode()
decoder = Decoder(testname, decode_table)
decoded = list(decoder.decode(len(approx_data)/2))
decoded += list(decoder.decode(len(approx_data)/2))
print approx_data == decoded
是否有可以更快地执行类似操作的模块?如果没有,有什么方法可以更改我的代码以使其更快?
最佳答案
关于python - 压缩此数据的更快方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16223787/
我有点想做 the reverse of this. 我不想解压缩并将收集文件添加到 S3 应用户要求: 生成一堆xml文件 使用一些图像(托管在 s3 上的预先存在的图像)压缩 xml 文件 下载
将此添加到域的虚拟主机后 AddOutputFilterByType DEFLATE application/javascript text/javascript text/css 响应头不包含任何内
在 Apache Im 中,通过将以下内容添加到我的 .htaccess 文件来启用输出压缩: # compress text, html, javascript, css, xml: AddOutp
是否可以以压缩格式将请求数据从浏览器发送到服务器? 如果是,我们该怎么做? 最佳答案 压缩从浏览器发送到服务器的数据是不受 native 支持 在浏览器中。 您必须找到一种解决方法,使用客户端语言(可
我正在寻找可以压缩JavaScript源代码的工具。我发现一些网络工具只能删除空格字符?但也许存在更好的工具,可以压缩用户的函数名称、字段名称、删除未使用的字段等。 最佳答案 经常用来压缩JS代码的工
使用赛马博彩场景,假设我有许多单独的投注来预测比赛的前 4 名选手 (superfecta)。 赌注如下... 1/2/3/4 1/2/3/5 1/2/4/3 1/2/4/5 1/2/5/3
我是一名实习生,被要求对 SQL 2008 数据压缩进行一些研究。我们想将 Outlook 电子邮件的几个部分存储在一个表中。问题是我们想将整个电子邮件正文存储在一个字段中,然后又想压缩它。使用 Ch
我目前有一个系统,用户可以在其中上传 MP4 文件,并且可以在移动设备上下载该文件。但有时,这些视频的大小超过 5MB,在我国,大多数人使用 2G。因此,下载大型视频通常需要 15-20 分钟。 有什
假设我有一个带有类型列的简单文档表: Documents Id Type 1 A 2 A 3 B 4 C 5 C 6 A 7 A 8 A 9 B 10 C 用户
我有一个较大字符串中的(子)字符串位置的 data.frame。数据包含(子)字符串的开头及其长度。可以很容易地计算出(子)字符串的结束位置。 data1 start length end #>
我想知道是否 文件加密算法可以设计成它也可以执行文件压缩的事件(任何活生生的例子?)。 我也可以将它集成到移动短信服务中,我的意思是短信吗? 另外我想知道二进制文件...如果纯文本文件以二进制编码
关闭。这个问题不满足Stack Overflow guidelines .它目前不接受答案。 想改善这个问题吗?更新问题,使其成为 on-topic对于堆栈溢出。 7年前关闭。 Improve thi
我们有几个具有大量 JavaScript 的 Java 项目,目前我们使用的是旧版本的 YUICompressor (2.4.2)。然而,我在这篇博文中发现 YUICompressor 正在 depr
从之前关于尝试提高网站性能的文章中,我一直在研究 HTTP 压缩。我读过有关在 IIS 中设置它的信息,但它似乎是所有 IIS 应用程序池的全局事物,我可能不允许这样做,因为还有另一个站点在其上运行。
我有一个 REST 服务,它返回一大块 XML,大约值(value) 150k。 例如http://xmlservice.com/services/RestService.svc/GetLargeXM
我正在尝试获取一个简单的 UglifyJS (v2.3.6) 示例来处理压缩。 具体来说,“未使用”选项,如果从未使用过,变量和函数将被删除。 这是我在命令行上的尝试: echo "function
我正在开发一个项目,如果我的磁盘出现问题,我将在使用 ZLIB 压缩内存块后将其发送到另一个磁盘。然后我计划下载该转储并用于进一步调试。这种压缩和上传将一次完成一个 block - 比如说 1024
LZW 压缩算法在压缩后增加了位大小: 这是压缩函数的代码: // compression void compress(FILE *inputFile, FILE *outputFile) {
我的问题与如何在 3D 地形上存储大量信息有关。这些信息应该是 secret 的,因为它们非常庞大,也应该被压缩。我选择了文件存储,现在我想知道将对象数据加密/压缩(或压缩/加密)到文件的最佳做法。
我使用以下代码来压缩我的文件并且效果很好,但我只想压缩子文件夹而不是在压缩文件中显示树的根。 public boolean zipFileAtPath(String sourcePath, Strin
我是一名优秀的程序员,十分优秀!