尝试编码时出错

时间:2016-06-02 14:15:02

标签: python file lzw

为什么我不能使用sourcecode = "myFile.txt" f = open(sourcecode, mode='rb')打开我的文件并压缩它?这对我来说都很新鲜。如果你们中的一些人能就如何解决问题给我一些建议,我会很高兴的。

def compress(uncompressed):
    """Compress a string to a list of output symbols."""

    sourcecode = "myFile.txt"
    f = open(sourcecode, mode='rb')   

    # Build the dictionary.
    dict_size = 256
    dictionary = dict((chr(i), chr(i)) for i in xrange(dict_size))
    # in Python 3: dictionary = {chr(i): chr(i) for i in range(dict_size)}

    w = ""
    result = []
    for c in uncompressed:
        wc = w + c
        if wc in dictionary:
            w = wc
        else:
            result.append(dictionary[w])
            # Add wc to the dictionary.
            dictionary[wc] = dict_size
            dict_size += 1
            w = c

    # Output the code for w.
    if w:
        result.append(dictionary[w])
    return result



def decompress(compressed):
    """Decompress a list of output ks to a string."""

    # Build the dictionary.
    dict_size = 256
    dictionary = dict((chr(i), chr(i)) for i in xrange(dict_size))
    # in Python 3: dictionary = {chr(i): chr(i) for i in range(dict_size)}

    w = result = compressed.pop(0)
    for k in compressed:
        if k in dictionary:
            entry = dictionary[k]
        elif k == dict_size:
            entry = w + w[0]
        else:
            raise ValueError('Bad compressed k: %s' % k)
        result += entry

        # Add w+entry[0] to the dictionary.
        dictionary[dict_size] = w + entry[0]
        dict_size += 1

        w = entry
    return result

compressed = compress(f)
print (compressed)
decompressed = decompress(compressed)
print (decompressed)

我发现此代码位于:http://rosettacode.org/wiki/LZW_compression#Python

1 个答案:

答案 0 :(得分:0)

一个问题是您在compress功能中打开文件。这意味着f在函数外部不可见,因此调用compress(f)会给您一个找不到f的错误。正确的语法是将行sourcecode = "myFile.txt"f = open(sourcecode, mode='rb')移到那里,以便您拥有:

sourcecode = "myFile.txt"
f = open(sourcecode, mode='rb') 
compressed = compress(f.read())
f.close() # don't forget to close open files

调用f.read()时请注意compressf本身就是一个文件描述符,f.read()是一个返回文件内容的文件描述符,作为compress()的参数给出的字符串