python2判断编码格式

 1 def getCoding(strInput):
 2     '''
 3     获取编码格式
 4     '''
 5     if isinstance(strInput, unicode):
 6         return "unicode"
 7     try:
 8         strInput.decode("utf8")
 9         return 'utf8'
10     except:
11         pass
12     try:
13         strInput.decode("gbk")
14         return 'gbk'
15     except:
16         pass
17         
18 def tran2UTF8(strInput):
19     '''
20     转化为utf8格式
21     '''
22     strCodingFmt = getCoding(strInput)
23     if strCodingFmt == "utf8":
24         return strInput
25     elif strCodingFmt == "unicode":
26         return strInput.encode("utf8")
27     elif strCodingFmt == "gbk":
28         return strInput.decode("gbk").encode("utf8")
29 
30 def tran2GBK(strInput):
31     '''
32     转化为gbk格式
33     '''
34     strCodingFmt = getCoding(strInput)
35     if strCodingFmt == "gbk":
36         return strInput
37     elif strCodingFmt == "unicode":
38         return strInput.encode("gbk")
39     elif strCodingFmt == "utf8":
40         return strInput.decode("utf8").encode("gbk")

 

posted on 2019-02-23 09:52  帅胡  阅读(512)  评论(0编辑  收藏  举报

导航