Advertisement
rfmonk

codecs_incremental_bz2.py

Jan 29th, 2014
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.24 KB | None | 0 0
  1. #1/usr/bin/env python
  2.  
  3. # this is from The Python
  4. # Standard Library by example
  5. # ISBN13: 9780321767349
  6.  
  7. import codecs
  8. import sys
  9.  
  10. from codecs_to_hex import to_hex
  11.  
  12. text = 'abcdefghijklmnopqrstuvwxyz\n'
  13. repetitions = 50
  14.  
  15. print 'Text length :', len(text)
  16. print 'Repetitions :', repetitions
  17. print 'Expected len:', len(text) * repetitions
  18.  
  19. # Encode the text several times to build up a large amount of data
  20. encoder = codecs.getincrementalencoder('bz2')()
  21. encoded = []
  22.  
  23. print
  24. print 'Encoding:',
  25. for i in range(repetitions):
  26.     en_c = encoder.encode(text, final=(i == repetitions - 1))
  27.     if en_c:
  28.         print '\nEncoded : {} bytes'.format(len(en_c))
  29.         encoded.append(en_c)
  30.     else:
  31.         sys.stdout.write('.')
  32.  
  33. bytes = ''.join(encoded)
  34. print
  35. print 'Total encoded length:', len(bytes)
  36. print
  37.  
  38. # Decode the byte string one byte at a time
  39. decoder = codecs.getincrementaldecoder('bz2')()
  40. decoded = []
  41.  
  42. print 'Decoding:',
  43. for i, b in enumerate(bytes):
  44.     final = (i + 1) == len(text)
  45.     c = decoder.decode(b, final)
  46.     if c:
  47.         print '\nDecoded : {} characters'.format(len(c))
  48.         print 'Decoding:',
  49.         decoded.append(c)
  50.     else:
  51.         sys.stdout.write('.')
  52.  
  53. print
  54.  
  55. restored = u''.join(decoded)
  56.  
  57. print
  58. print 'Total uncompressed length:', len(restored)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement