-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlzw.py
More file actions
79 lines (62 loc) · 1.79 KB
/
Copy pathlzw.py
File metadata and controls
79 lines (62 loc) · 1.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
def encode_lzw(data):
letter=[]
position=[]
dicSize=128
dictionary = {}
for i in range(0,dicSize):
c=chr(i)
dictionary[c]=i
foundChars=""
result=[]
for char in data:
charsToAdd=foundChars+char
if charsToAdd in dictionary:
foundChars=str(dictionary[charsToAdd])
else:
result.append(foundChars)
dictionary[charsToAdd]=dicSize
dicSize=dicSize+1
foundChars=str(dictionary[char])
if (foundChars!=""):
result.append(foundChars)
return result
def decode_lzw(encodedNums):
dictSize=128
dictionary = {}
for i in range(0,dictSize):
c=chr(i)
dictionary[i]=c
characters=dictionary[int(encodedNums[0])]
decodedString=""
decodedString=decodedString+characters
for i in range(1,len(encodedNums)):
if int(encodedNums[i]) in dictionary:
string=dictionary[int(encodedNums[i])]
else:
string=characters+characters[0]
decodedString=decodedString+string
dictionary[dictSize]=characters+string[0]
dictSize=dictSize+1
characters=string
return decodedString
file = input("Enter the filename you want to compress: ")
with open(file, 'r') as f:
stringToEncode = f.read()
result=encode_lzw(stringToEncode)
print(result)
output = open("encoded.txt","w+")
size = len(result)
for i in range(size):
word = str(result[i]) + ','
output.write(word)
print("Compressed file generated as encoded.txt")
file = input("Enter the filename you want to decompress:")
f = open(file, "r").readline()
newList = f[1:len(f)-1].split(",")
encodedNums = []
for word in newList:
if word == '':
break
encodedNums.append(int(word))
s=decode_lzw(encodedNums)
print(s)