Python arbitrary encoding to UTF8 or Unicode

Source: Internet
Author: User

# Encoding:utf-8
‘‘‘
Created on February 8, 2015

@author: Zhang Peng Cheng [email protected]
@copyright: All rights reserved, respect labor success, reprint and amend please indicate the author
‘‘‘
Import Traceback

Import Chardet

def Mytoutf8 (s):
return Mytounicode (s). Encode (' Utf-8 ')

def mytounicode (s):
If type (s) = = Type (U '):
# print ' 1 '
return s
Try
# print ' 2 '
s = S.decode (' Utf-8 ')
Except
Try
# print ' 3 '
s = S.decode (' GB18030 ')
Except
print ' ***error:decode string ({0}) '. Format (repr (s))
Print Traceback.print_exc ()
s = repr (s)
# print ' 4 '
return s

if __name__ = = ' __main__ ':
# Test China I Love you
# Utf-8
s = ur ' China i love you '
Print repr (s), S
CC = [' Utf-8 ', ' gb18030 ', ' GBK ']
fn = [Mytounicode, Mytoutf8,]
For F in FN:
For C in cc:
# print ' = ' * 80
print ' {0:<20} ({1:10}) = {2:<50}, {3} '. Format (f.__name__, C, repr (f (S.encode (c))), F (S.encode (c)))

Python arbitrary encoding to UTF8 or Unicode

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.