2012-10-13 2 views
16

아스키 기반 문자열을 압축하는 방법을 찾고 있는데, 어떤 도움이 필요합니까?파이썬 - 압축 아스키 문자열

또한 압축을 풀어야합니다. 나는 zlib를 시도했지만 아무 도움도받지 못했다.

문자열을 더 짧은 길이로 압축하려면 어떻게해야합니까?

코드 :

def compress(request): 
    if request.POST: 
     data = request.POST.get('input') 
     if is_ascii(data): 
      result = zlib.compress(data) 
      return render_to_response('index.html', {'result': result, 'input':data}, context_instance = RequestContext(request)) 
     else: 
      result = "Error, the string is not ascii-based" 
      return render_to_response('index.html', {'result':result}, context_instance = RequestContext(request)) 
    else: 
     return render_to_response('index.html', {}, context_instance = RequestContext(request)) 
+0

http://en.literateprograms.org/Huffman_coding_(Python) – GodMan

+0

참조 zlib가 도움이되지 않은 이유는 무엇입니까? – Sergey

+0

문자열을 반환하려고했지만 작동하지 않았습니다. – moenad

답변

23

을위한 ~ 30 % 더 많은 공간을 사용합니다!

다음 코드를 고려하십시오.

import zlib 
import bz2 

def comptest(s): 
    print 'original length:', len(s) 
    print 'zlib compressed length:', len(zlib.compress(s)) 
    print 'bz2 compressed length:', len(bz2.compress(s)) 

빈 문자열을 사용해 보겠습니다.

In [15]: comptest('') 
original length: 0 
zlib compressed length: 8 
bz2 compressed length: 14 

그래서 zlib는 추가 8자를 생성하고 bz2 14. 압축 방법은 일반적으로 신장 프로그램에 의한 사용을위한 압축 된 데이터의 앞에 '헤더'을 넣어. 이 머리글은 출력 길이를 늘립니다.

한 단어를 테스트 해 봅시다.

In [16]: comptest('test') 
original length: 4 
zlib compressed length: 12 
bz2 compressed length: 40 

헤더의 길이를 빼더라도 압축하면 단어가 더 짧아지지 않습니다. 이 경우에는 압축 할 것이 거의 없기 때문입니다. 문자열의 대부분의 문자는 한 번만 발생합니다. 이제 짧은 문장을 위해;

In [17]: comptest('This is a compression test of a short sentence.') 
original length: 47 
zlib compressed length: 52 
bz2 compressed length: 73 

다시 압축 출력은 입력 텍스트 보다 크다. 문자의 길이가 제한되어 있으므로 반복이 거의 없으므로 압축이 잘되지 않습니다.

실제로 작동하려면 압축을 위해 상당히 긴 텍스트 블록이 필요합니다.

In [22]: rings = ''' 
    ....:  Three Rings for the Elven-kings under the sky, 
    ....:  Seven for the Dwarf-lords in their halls of stone, 
    ....:  Nine for Mortal Men doomed to die, 
    ....:  One for the Dark Lord on his dark throne 
    ....:  In the Land of Mordor where the Shadows lie. 
    ....:  One Ring to rule them all, One Ring to find them, 
    ....:  One Ring to bring them all and in the darkness bind them 
    ....:  In the Land of Mordor where the Shadows lie.''' 

In [23]: comptest(rings)      
original length: 410 
zlib compressed length: 205 
bz2 compressed length: 248 
+0

파이썬 3의 경우,'zlib.compress'와'bz2.compress'에 대한 입력은 바이트로 이루어져야하므로 먼저 문자열을'.encode()'해야합니다 – mschrimpf

6

당신은, 당신은 아무것도 ZLIB를 공급 할 수 있습니다 데이터가 아스키를 할 필요가 없습니다

>>> import zlib 
>>> a='aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' # + any binary data you want 
>>> print zlib.compress(a) 
x�KL$ 
� 
>>> 

당신은 아마 여기에 원하는 것은 - 아스키 문자열로 데이터를 압축 ? 내가 여기 있니?
그렇다면 압축 된 데이터를 코딩하기위한 알파벳이 매우 작다는 것을 알아야하므로 => 더 많은 기호를 사용하게됩니다. base64로 바이너리 데이터를 코드 예를 들어

는 (당신은 ASCII 문자열을 얻을 것이다) 그러나 당신은 항상 문자열의 길이를 줄일 수 없습니다 압축을 사용하여 해당