python3环境下的全角与半角转换代码和测试
————开始———
全角和半角转换是文本预处理的常见工作之一,然而现在网上一搜python的相关代码,几乎都是python2版本的,因此根据人角和半角的转换规律,将其代码撰写如下:
1、全角与半角之间的转换规律
角字符unicode编码从65281~65374 (十六进制 0xFF01 ~ 0xFF5E)
半角字符unicode编码从33~126 (十六进制 0x21~ 0x7E)
-
特殊的:
空格比较特殊,全角为 12288(0x3000),半角为 32(0x20)
除空格外,全角/半角按unicode编码排序在顺序上是对应的(半角 + 0x7e= 全角),所以可以直接通过用+-法来处理非空格数据,对空格单独处理。
2、转换代码脚本(python3)
def strQ2B(ustring): """把字符串半角转全角""" ss = [] for s in ustring: rstring = "" for uchar in s: 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) ss.append(rstring) return ''.join(ss)
from string import punctuation
def strB2Q(ustring): """把字符串全角转半角""" ss = [] for s in ustring: rstring = "" for uchar in s: inside_code = ord(uchar) if inside_code == 32: # 全角空格直接转换 inside_code = 12288 elif (inside_code >= 33 and inside_code <= 126): # 全角字符(除空格)根据关系转化 inside_code += 65248 rstring += chr(inside_code) ss.append(rstring) return ''.join(ss) if __name__ == '__main__': a = strB2Q("你好pythonabdalduizxcvbnm") print(a) b = strQ2B(a) print(b)
c = strB2Q(punctuation)
批量替换全角半角符号
————结尾—————
浙公网安备 33010602011771号