Implementing decompression algorithm but get "key error: 0"

178 Views Asked by At

**Compression Function **

def lzwCompressionText (text):
start= time.time()
with open(text, 'r',encoding="utf-8") as file:
    data = file.read()
#print("data",data)
#Costruzion,del del Dizionario
print("Compressing")
lenDictionary = 256
dictionary = defaultdict(dict)
print("iniziale", dictionary)
compressed = []
stringSaved=""


for string_symbol in data:
    sc =  stringSaved + string_symbol
    if sc in dictionary :
        stringSaved = sc
    else:
        compressed.append(dictionary[stringSaved])
        dictionary[sc] = lenDictionary
        lenDictionary += 1
        stringSaved= string_symbol
if stringSaved in dictionary:
    compressed.append(dictionary[stringSaved])
   # print ("Compressed", compressed)

output= open("CompreText.bin", "wb")
pickle.dump(compressed, output)
stop = time.time()
finalCompression = (stop - start)
minute = int(finalCompression / 60)
seconds = int(finalCompression % 60)
print("Minute :", minute,"second",seconds)

output.close()

return compressed

I am implementing the decompression algorithm. But this error "key error: 0" comes.

In this part of the code, the bin file generated by the compression file is loaded, the vocabulary is initialized.

def lzwDecompressionText (pathText) :
    loadCompressed = open ("CompreText.bin","rb")
    compressed = pickle.load(loadCompressed)    
    print("", compressed)
    lenDictionary = 256
    dictionary = defaultdict(dict)
       
    s = pathText= compressed.pop(0)
    
    for k in compressed :
        if k in dictionary:
            ins = dictionary[k]
        elif k == lenDictionary:
            ins = s + s[0]
        else:
            raise ValueError()
        pathText += ins
        dictionary[lenDictionary] = s + ins[0]
        lenDictionary +=1
        s = ins

When the dictionary is searched it gives me an error: Key error "0". I also tried to edit the dictionary but I always get the same error.

Traceback (most recent call last):
  File "c:/Users/anton/Documents/GitHub/Project-LZW/LZW-Project/test.py", line 21, in <module>
    lzwDecompressionText(pathText)
  File "c:\Users\anton\Documents\GitHub\Project-LZW\LZW-Project\textLzw.py", line 68, in lzwDecompressionText
    ins = s + s[0]
KeyError: 0
0

There are 0 best solutions below