Advertisement
Guest User

Untitled

a guest
May 22nd, 2015
231
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.12 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # encoding: utf-8
  3. #
  4. # Copyright (c) 2010 Doug Hellmann. All rights reserved.
  5. #
  6. """Translating between encodings on the fly.
  7. """
  8. #end_pymotw_header
  9.  
  10. from codecs_to_hex import to_hex
  11.  
  12. import codecs
  13. from cStringIO import StringIO
  14.  
  15. # Raw version of the original data.
  16. data = u'pi: \u03c0'
  17.  
  18. # Manually encode it as UTF-8.
  19. utf8 = data.encode('utf-8')
  20. print 'Start as UTF-8 :', to_hex(utf8, 1)
  21.  
  22. # Set up an output buffer, then wrap it as an EncodedFile.
  23. output = StringIO()
  24. encoded_file = codecs.EncodedFile(output, data_encoding='utf-8',
  25. file_encoding='utf-16')
  26. encoded_file.write(utf8)
  27.  
  28. # Fetch the buffer contents as a UTF-16 encoded byte string
  29. utf16 = output.getvalue()
  30. print 'Encoded to UTF-16:', to_hex(utf16, 2)
  31.  
  32. # Set up another buffer with the UTF-16 data for reading,
  33. # and wrap it with another EncodedFile.
  34. buffer = StringIO(utf16)
  35. encoded_file = codecs.EncodedFile(buffer, data_encoding='utf-8',
  36. file_encoding='utf-16')
  37.  
  38. # Read the UTF-8 encoded version of the data.
  39. recoded = encoded_file.read()
  40. print 'Back to UTF-8 :', to_hex(recoded, 1)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement