Вот немного доработанный код а то за вчерашний сегодня стыдно
Код | #!/usr/bin/env python # -*- coding: utf-8 -*-
import sys import os import time
# The initial LZW tables that maps codes to strings and vice-versa. code_to_str = [chr(i) for i in range(256)] str_to_code = dict((chr(i), i) for i in range(256))
def compress(seq): ''' Returns an LZW compressed list of the input character sequence. ''' output = [] table = dict(str_to_code)
s = '' for ch in seq: it = s + ch if it in table: s = it else: output.append(table[s]) table[it] = len(table) s = ch output.append(table[s]) return output
def decompress(seq): ''' Returns a decompressed list of the LZW compressed input. ''' table = code_to_str[:] prevcode = seq[0]
output = [] output.append(table[prevcode])
for code in seq[1:]: try: entry = table[сcode] #в ccode убрать лишнюю c (сбивается форматирование сообщения на форуме :-) ) except IndexError: # The lzw special case when code is not yet defined. entry = table[prevcode] entry += entry[0] output.append(entry) table.append(table[prevcode] + entry[0]) prevcode = code return output
# MAIN if len(sys.argv) != 4: print 'Usage: LZW.py [c|d] [path]InputFileName [path]OutputFileName' sys.exit() mode = sys.argv[1] # compress/decompress inputFile = sys.argv[2] outputFile = sys.argv[3]
fileSize = os.path.getsize(inputFile) print fileSize
f2 = open(outputFile, "w", 1)
if mode == 'c': t = time.time() f1 = open(inputFile, "r", 1) s = "".join([line for line in f1]) f1.close() print 'Вход:', s compressed = compress(s) outputList = [] for i in range(len(compressed)): #print compressed[i] f2.write(str(compressed[i]) + '\n') outputList.append(compressed[i]) f2.close print 'Выход:', outputList print 'Время сжатия:', time.time() - t fileSize = os.path.getsize(outputFile) print fileSize
elif mode == 'd': t = time.time() f1 = open(inputFile, "r", 1) s = [] for line in f1: if len(line) > 0: s.append(int(line[:len(line)-1])) f1.close() print 'Вход:', s data = decompress(s) s = "".join([line for line in data]) print 'Выход:', s f2.write(s) f2.close print 'Время декодирования: ', time.time() - t fileSize = os.path.getsize(outputFile) print fileSize
|
если ничего не подскажите буду пробовать сдать это  |