2. 映射后的数据如何编码为字节?这个就是具体的编码规则:目前最主流的是UTF-8,同样,它也是变字长的。
python3中的str都是unicode的:“The default encoding for Python source code is UTF-8”
python3中的encode:按照encode()括号中的参数对字符串进行编码,就是生成bytes。
所以:
In:'中文'.encode('utf-8')
Out:b'\xe4\xb8\xad\xe6\x96\x87'
这里的b就是Byte,\x表示这个x是被转义的,意思就是0x。又如:
In: 'abc'.encode('utf-8')
Out: b'abc'
上面的b'a'其实表示的是数字97,b'a'的意思就是字符串'a'的binary数字:
[In]:'abc'.encode('utf-8')[0]
[Out]: 97
同时可以把b'\x'进行解码,即:
In:b'\xe4\xb8\xad\xe6\x96\x87'.decode('utf-8')
Out:'中文'
除了encode('utf-8')外,用ord可以获得单个utf-8字符对应的数字:
In [60]: ord('a')
Out[60]: 97
In [61]: ord('a') #这个是全角的a
Out[61]: 65345
除了decode('utf-8')外,用chr可以获得数字对应的utf-8字符:
In [62]: chr(97)
Out[62]: 'a'
除了unicode还有别的编码标准吗?有啊,比如我国的GBK,别名也叫cp936。
全角和半角之分,是指同样一个意义的字符,显示的大小不同.具体来说,全角和半角的编码是两个结果:
In [70]: "mn".encode('utf-8')
Out[70]: b'\xef\xbd\x8d\xef\xbd\x8e
[In]:"mn".encode('utf-8')
[Out]:b'mn'
它们有什么对应关系呢?(引自这里)
转换说明
全角半角转换说明
有规律(不含空格):
全角字符unicode编码从65281~65374 (十六进制 0xFF01 ~ 0xFF5E)
半角字符unicode编码从33~126 (十六进制 0x21~ 0x7E)
特例:
空格比较特殊,全角为 12288(0x3000),半角为 32(0x20)
除空格外,全角/半角按unicode编码排序在顺序上是对应的(半角 + 0x7e= 全角),所以可以直接通过用+-法来处理非空格数据,对空格单独处理。
代码在此基础上改动一下(将unichr改为chr即可,适应python3),即:
def strQ2B(ustring):
"""全角转半角"""
rstring = ""
for uchar in ustring:
inside_code=ord(uchar)
if inside_code == 12288:#全角空格直接转换
inside_code = 32
elif (inside_code >= 65281 and inside_code <= 65374): #全角字符(除空格)根据关系转化
inside_code -= 65248
rstring += chr(inside_code)
return rstring
In [69]: strQ2B('你好python')
Out[69]: '你好python'
Python:常用函数封装: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