导航:首页 > 编程语言 > python查看字符串编码格式

python查看字符串编码格式

发布时间:2022-10-21 14:03:26

1. python怎么知道一个字符串的编码方式

字符串的编码,有很多种如utf-8,gb2312,gbk,gb18030,bz2,zlib,big5,bzse64

python 对编码的处理有两个方法,decode()和 encode()方法

a='你好'
b='python'
printa.decode('utf-8').encode('gbk')##decode方法把字符串转换为unicode对象,然后通过encode方法转换为指定的编码字符串对象
printb.decode('utf-8')##decode方法把字符串转换为unicode对象

所以要让python(或者说机器)来识别字符串的编码,是一件很困难的事。编码就是汉字和整数之间的对应,同一个整数,可以在不同的编码中,都有对应的汉字。比如下面的例子,比特流'xe6xb0xb4xe5xa3xb6'在四种编码中都有对应的汉字,但只有在utf-8编码下,它对应的汉字才有意义。我们可以一眼看出这点,可是要让计算机做到这点,就很难了。

>>>s='水壶'
>>>s
18:'xe6xb0xb4xe5xa3xb6'
>>>printunicode(s,'big5')
瘗游ㄥ
>>>printunicode(s,'gbk')
姘村6
>>>printunicode(s,'gb2312')
姘村6
>>>printunicode(s,'utf-8')
水壶

2. python 判断一个字符能否用gbk和utf8编码

使用chardet库。它会去猜测文本文件的编码,并返回形如:
编码类型:utf-8
置信度:0.9
这样的结果,也就是说chardet断定该文件有90%的可能性是utf-8编码的。
不过chardet的缺陷就是,它不能完全100%确定文件的编码类型。
目前我的做法是,如果置信度超过0.95,那么就认定chardet的判断结果是正确的。否则,再加上一些人机交互操作进行判断。

目前,chardet库官网提供的版本只适用于Python 2,如果您使用的是Python 3.x,我可以另外上传一个。

3. Python中中文字符串怎么处理

如果处理的字符串中出现中文表示的字符,要想不出错,就得转成unicode编码了。具体的方法有:
1、decode(),将其他边编码的字符串转换成unicode编码,如str1.decode('gb2312'),表示将gb2312编码的字符串str1转换成unicode编码;
2、encode(),将unicode编码转换成其他编码的字符串,如str2.encode('gb2312'),表示将unicode编码的字符串str2转换成gb2312编码;
3、unicode(),同decode(),将其他编码的字符串转换成unicode编码,如unicode(str3, 'gb2312'),表示将gb2312编码的字符串str3转换成unicode编码。
转码的时候一定要先搞明白字符串str是什么编码,然后decode成unicode,最后再encode成其他编码。
另外,对一个unicode编码的字符串在进行解码会出错,所以在编码未知的情况下要先判断其编码方式是否为unicode,可以用isinstance(str, unicode)。
不仅是中文,以后处理含非ascii编码的字符串时,都可以遵循以下步骤:
1、确定源字符的编码格式,假设是utf8;
2、使用unicode()或decode()转换成unicode编码,如str1.decode('utf8'),或者unicode(str1, 'utf8');
3、把处理后字符串用encode()编码成指定格式。

4. python怎样查看当前字符串的编码格式

查看当前字符串的编码格式的代码为:Type "now", "right", "credits" or "license" for more information.

5. 如何辨认python的编码格式是unicode

Python文件里开头有coding:utf-8,则说明这个Python文件是Unicode编码。
在Python3中字符串是默认使用Unicode的,python2.x则得用u来表示它是Unicode字符串,如a=u“abcdefg”。type函数可以验证

6. 如何设置python的编码格式为utf-8

python的编码格式?
#coding=utf-8
这是文档编码
import sys
sys.setdefaultencoding("utf-8")
这是设置默认编码方式为utf-8
xx.encode("utf-8")
这是字符串编码操作
import codecs
codecs.open(xx,'r','utf-8"),这是文件编码读取方式

7. Python2.7 中文字符编码,使用Unicode时,选择什么编码格式

关于编码和乱码的问题,我简单讲一下。

通常问这类问题的人是混淆了若干个不同的概念,并且他们自己也没有意识到自己混淆了这些概念的。

8. python怎么判断中文字符编码

#!/usr/bin/env python
# -*- coding:GBK -*-

"""汉字处理的工具:
判断unicode是否是汉字,数字,英文,或者其他字符。
全角符号转半角符号。"""

__author__="internetsweeper <[email protected]>"
__date__="2007-08-04"

def is_chinese(uchar):
"""判断一个unicode是否是汉字"""
if uchar >= u'\u4e00' and uchar<=u'\u9fa5':
return True
else:
return False

def is_number(uchar):
"""判断一个unicode是否是数字"""
if uchar >= u'\u0030' and uchar<=u'\u0039':
return True
else:
return False

def is_alphabet(uchar):
"""判断一个unicode是否是英文字母"""
if (uchar >= u'\u0041' and uchar<=u'\u005a') or (uchar >= u'\u0061' and uchar<=u'\u007a'):
return True
else:
return False

def is_other(uchar):
"""判断是否非汉字,数字和英文字符"""
if not (is_chinese(uchar) or is_number(uchar) or is_alphabet(uchar)):
return True
else:
return False

def B2Q(uchar):
"""半角转全角"""
inside_code=ord(uchar)
if inside_code<0x0020 or inside_code>0x7e: #不是半角字符就返回原来的字符
return uchar
if inside_code==0x0020: #除了空格其他的全角半角的公式为:半角=全角-0xfee0
inside_code=0x3000
else:
inside_code+=0xfee0
return unichr(inside_code)

def Q2B(uchar):
"""全角转半角"""
inside_code=ord(uchar)
if inside_code==0x3000:
inside_code=0x0020
else:
inside_code-=0xfee0
if inside_code<0x0020 or inside_code>0x7e: #转完之后不是半角字符返回原来的字符
return uchar
return unichr(inside_code)

def stringQ2B(ustring):
"""把字符串全角转半角"""
return "".join([Q2B(uchar) for uchar in ustring])

def uniform(ustring):
"""格式化字符串,完成全角转半角,大写转小写的工作"""
return stringQ2B(ustring).lower()

def string2List(ustring):
"""将ustring按照中文,字母,数字分开"""
retList=[]
utmp=[]
for uchar in ustring:
if is_other(uchar):
if len(utmp)==0:
continue
else:
retList.append("".join(utmp))
utmp=[]
else:
utmp.append(uchar)
if len(utmp)!=0:
retList.append("".join(utmp))
return retList

if __name__=="__main__":
#test Q2B and B2Q
for i in range(0x0020,0x007F):
print Q2B(B2Q(unichr(i))),B2Q(unichr(i))

#test uniform
ustring=u'中国 人名a高频A'
ustring=uniform(ustring)
ret=string2List(ustring)
print ret

以上转自http://hi..com/fenghua1893/item/d1a71d5ac47ffdcfd3e10cd1

这个问题是做 MkIV 预处理程序时搞定的,就是把一个混合了中英文混合字串分离为英文与中文的子字串,譬如,将 ”我的 English 学的不好“ 分离为 “我的"、" English ” 与 "学的不好" 三个子字串。
1. 中英文混合字串的统一编码表示中英文混合字串处理最省力的办法就是把它们的编码都转成 Unicode,让一个汉字与一个英文字母的内存位宽都是相等的。这个工作用 Python 来做,比较合适,因为 Python 内码采用的是 Unicode,并且为了支持 Unicode 字串的操作,Python 做了一个 Unicode 内建模块,把 string 对象的全部方法重新实现了一遍,另外提供了 Codecs 对象,解决各种编码类型的字符串解码与编码问题。
譬如下面的 Python 代码,可实现 UTF-8 编码的中英文混合字串向 Unicode 编码的转换:# -*-
coding:utf-8 -*-
a = "我的 English 学的不好"
print type(a),len (a), a
b = unicode (a, "utf-8")
print type(b), len (b), b字符串 a 是 utf-8 编码,使用 python 的内建对象 unicode 可将其转换为 Unicode 编码的字符串 b。上述代码执行后的输出结果如下所示,比较字串 a 与字串 b 的长度,显然 len (b) 的输出结果是合理的。<type 'str'> 27 我的 English 学的不好
<type 'unicode'> 15 我的 English 学的不好要注意的一个问题是 Unicode 虽然号称是“统一码”,不过也是存在着两种形式,即:
UCS-2:为 16 位码,具有 2^16 = 65536 个码位; UCS-4:为 32 位码,目前的规定是其首字节的首位为 0,因此具有 2^31 = 2147483648 个码位,不过现在的只使用了 0x00000000 - 0x0010FFFF 之间的码位,共 1114112 个。
使用Python sys 模块提供的一个变量 maxunicode 的值可以判断当前 Python 所使用的 Unicode 类型是 UCS-2 的还是 UCS-4 的。import sys
print sys.maxunicode若 sys.maxunicode 的值为 1114111,即为 UCS-4;若为 65535,则为 UCS-2。

2. 中英文混合字串的分离一旦中英文字串的编码获得统一,那么对它们进行分裂就是很简单的事情了。首先要为中文字串与英文字串分别准备一个收集器,使用两个空的字串对象即可,譬如 zh_gather 与 en_gather;然后要准备一个列表对象,负责按分离次序存储 zh_gather 与 en_gather 的值。下面这个 Python 函数接受一个中英文混合的 Unicode 字串,并返回存储中英文子字串的列表。def split_zh_en (zh_en_str):

zh_en_group = []
zh_gather = ""
en_gather = ""
zh_status = False

for c in zh_en_str:
if not zh_status and is_zh (c):
zh_status = True
if en_gather != "":
zh_en_group.append ([mark["en"],en_gather])
en_gather = ""
elif not is_zh (c) and zh_status:
zh_status = False
if zh_gather != "":
zh_en_group.append ([mark["zh"], zh_gather])
if zh_status:
zh_gather += c
else:
en_gather += c
zh_gather = ""

if en_gather != "":
zh_en_group.append ([mark["en"],en_gather])
elif zh_gather != "":
zh_en_group.append ([mark["zh"],zh_gather])

return zh_en_group上述代码所实现的功能细节是:对中英文混合字串 zh_en_str 的遍历过程中进行逐字识别,若当前字符为中文,则将其添加到 zh_gather 中;若当前字符为英文,则将其添加到 en_gather 中。zh_status 表示中英文字符的切换状态,当 zh_status 的值发生突变时,就将所收集的中文子字串或英文子字串添加到 zh_en_group 中去。
判断字串 zh_en_str 中是否包含中文字符的条件语句中出现了一个 is_zh () 函数,它的实现如下:def is_zh (c):
x = ord (c)
# Punct & Radicals
if x >= 0x2e80 and x <= 0x33ff:
return True

# Fullwidth Latin Characters
elif x >= 0xff00 and x <= 0xffef:
return True

# CJK Unified Ideographs &
# CJK Unified Ideographs Extension A
elif x >= 0x4e00 and x <= 0x9fbb:
return True
# CJK Compatibility Ideographs
elif x >= 0xf900 and x <= 0xfad9:
return True

# CJK Unified Ideographs Extension B
elif x >= 0x20000 and x <= 0x2a6d6:
return True

# CJK Compatibility Supplement
elif x >= 0x2f800 and x <= 0x2fa1d:
return True

else:
return False这段代码来自 jjgod 写的 XeTeX 预处理程序。
对于分离出来的中文子字串与英文子字串,为了使用方便,在将它们存入 zh_en_group 列表时,我对它们分别做了标记,即 mark["zh"] 与 mark["en"]。mark 是一个 dict 对象,其定义如下:mark = {"en":1, "zh":2}如果要对 zh_en_group 中的英文字串或中文字串进行处理时,标记的意义在于快速判定字串是中文的,还是英文的,譬如:for str in zh_en_group:
if str[0] = mark["en"]:
do somthing
else:
do somthing

9. python怎么查看字符串编码

安装chardet模块
chardet文件夹放在/usr/lib/python2.4/site-packages目录下

[root@sha-sso-data01 chardet]# python
Python 2.4.3 (#1, Sep 21 2011, 19:55:41)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-51)] on linux2
Type "help", "right", "credits" or "license" for more information.
>>> import chardet
>>> chardet.detect("我")
{'confidence': 0.505, 'encoding': 'utf-8'}
>>>

阅读全文

与python查看字符串编码格式相关的资料

热点内容
程序员的种类及名称 浏览:290
美国程序员薪资 浏览:12
黑石通汇证券服务器什么时候到期 浏览:391
东方财富app里我的关注怎么看 浏览:747
bm3d单反级降噪算法 浏览:457
华为安卓机激活时间怎么查询 浏览:850
如何用优盘重装服务器系统 浏览:317
日本结婚三代算法 浏览:920
皓强工具解压步骤 浏览:690
部队抗洪抢险命令范文 浏览:888
欧姆龙plc编程软件使用教程 浏览:594
ai文件pdf 浏览:912
腾讯云服务器挂载混合云 浏览:758
智能小车用什么单片机 浏览:463
java怎么给窗口关闭 浏览:940
列举51单片机的寻址方式 浏览:706
剪辑app怎么写长篇文字 浏览:400
app专属流量过月租怎么不更新 浏览:655
王者程序员都有谁 浏览:78
给牛换脚掌解压 浏览:389