0

我正在使用 LZ77 压缩程序,当我尝试压缩 116Kb 文件时,处理时间太长。我的代码有什么问题吗?我怎样才能提高算法的处理时间?

import fileinput

class Assign:

    def pattern(self, data):

        self.skip = []

        self.m = len(data)
        for k in range(256): self.skip.append(self.m)

        for k in range(self.m - 1): self.skip[ord(data[k])] = self.m - k - 1

        self.skip = tuple(self.skip)

        self.data = data
    def find(self, text):
        n = len(text)
        if self.m > n: return -1
        k = self.m - 1
        while k < n:
            j = self.m - 1; i = k
            while j >= 0 and text[i] == self.data[j]:
                j -= 1; i -= 1
            if j == -1: return i + 1
            k += self.skip[ord(text[k])]
        return -1

class LZ77:

    def __init__(self, data):
        self.position = 0
        self.window = ""
        self.stream = data
        self.streamSize = len(self.stream)
        self.search = Assign()
    def Encode(self):
        p = 0
        c = ''
        lastresult = 0
        found = 0
        for i in range(self.streamSize):
            self.search.pattern(self.stream[self.position:self.position+i+1])
            result = self.search.find(self.window)
            if result < 0: break
            lastresult = result
            found = 1
        c = self.stream[self.position+i]
        p = lastresult
        B = 0
        if i > 0: B = self.position - p
        L = i
        if self.streamSize > 0:
            self.position += i + 1
            self.streamSize -= i + 1
            self.window = self.stream[:self.position]
        #print B,L,c
        return ((B, L), c)



    def Encoder(self):

        output = ""

        length = self.streamSize
        while self.streamSize > 0:
            ((B, L), C) = self.Encode()
            output += str(B) +   str(L) +  C
        return (output)

def aiyoo(#filename):

    enter = raw_input("enter the filename to which the original file is to be compressed to")
    enter1 = enter
    fob1 = open(enter,'wb')
    original = ''
    print filename
    #fob = open(filename,'rb')
    #numlines = 0
    """while True:
        c = fob.read(1)
        if not c:
            print "End of file"
            break
        else :"""
    for line in fileinput.input(['hello.txt']): #size of hello.txt is 116kb   
        original = line
        lz = LZ77(original)
        stream = lz.Encoder()#, streamSize = lz.Encoder()
        fob1.write(stream)
    """for i in fob:
        original = i
        lz = LZ77(original)
        stream = lz.Encoder()#, streamSize = lz.Encoder()
        fob1.write(stream)"""
    #fob.close()
    fob1.close()
    return enter
4

2 回答 2

0

在问这样的问题之前,您应该分析您的代码以找出哪个部分花费的时间最多。

但无论如何,我看到你已经实现了一个子字符串搜索功能。find改用字符串方法应该可以显着提高速度。

另请注意,在 Python 中实现的压缩算法不会像例如在 Python 中实现的那样快。C,甚至没有关闭。

于 2013-02-04T08:04:40.757 回答
0

lz77 在真正的归档器(如 zip 和 rar)中的工作方式如下:将具有相同前 3-4 个字节的所有位置插入同一个哈希桶中,然后我们仅在这些条目中搜索最长匹配,通常将 serarch 限制为8-32位

于 2013-05-21T09:50:34.193 回答