尝试编码时出错

Error when trying to encode

为什么我不能使用 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

一个问题是您在 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

调用compress时注意f.read()f 本身是一个文件描述符,f.read() 是 returns 文件内容作为字符串作为参数提供给 compress()