python全角和半角之间的转换

时间:2022-06-12 17:51:57

源文件格式如下:

113871641994/m 年/q 7/m  /n 月/n ,/w 完成/v 第二/m 稿/Ng

11387163 /n 1992/m 年/q 底/f ,/w 在/p 妞妞/nr 死/v 后/f 一/m 年/q ,/w 我/r 把/p 自己/r 关/v 在/p 屋/n 里/f ,/w 开始/v 写/v 这/r 本/q 书/n ,/w 于/p 1993/m 年/q  /n 7/m 月/n 写/v 出/v 初稿/n

目标去掉词性标注

python全角和半角之间的转换

结果发现中间的空格没去掉,最后发现原因是:全角的空格无法匹配

python全角和半角之间的转换

对应的编码为:

python全角和半角之间的转换

发现前边的空格是全角空格。

空格比较特殊,全角为12288(0x3000)

有规律(不含空格):

全角字符unicode编码从65281~65374(十六进制0xFF01~0xFF5E)

半角字符unicode编码从33~126(十六进制0x21~0x7E)

特例:

空格比较特殊,全角为12288(0x3000),半角为32(0x20)

除空格外,全角/半角按unicode编码排序在顺序上是对应的(半角+0x7e=全角),所以可以直接通过用+-法来处理非空数据,对空格单独处理。

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 += unichr(inside_code)
return rstring

def strB2Q(ustring):
"""半角转全角"""
rstring = ""
for uchar in ustring:
inside_code=ord(uchar)
if inside_code == 32: #半角空格直接转化
inside_code = 12288
elif inside_code >= 32 and inside_code <= 126: #半角字符(除空格)根据关系转化
inside_code += 65248

rstring += unichr(inside_code)
return rstring

程序代码如下:

#encoding=utf8
#设置文件的编码
import sys
import codecs
import re
reload(sys)
sys.setdefaultencoding('utf-8')
print(sys.getdefaultencoding())
#读文件操作
#使用codec包进行文件的读取,在使用open()函数时指定编码的类型:
text_file = codecs.open("liter_time.10", "r", encoding="gbk")
out_file = codecs.open("out.txt", "w", encoding="utf-8")
k = 0

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 += unichr(inside_code)
return rstring

for line in text_file:
line.strip()
# m_home=homeLine.match(line)
# print(m_home.group())
line=strQ2B(line)
print(line)
#去掉行首
line = re.sub("^[0-9]+\s*", "", line)
print(line)
#去掉/n词性标注
line = re.sub("/\w*", "", line)
print(line)
#去掉空格
line = re.sub("\s*", "", line)
print(line)
line += "\n"
out_file.write(line.encode('utf-8'))
# break
k = k + 1
if( k > 5 ):
break

text_file.close()
out_file.close()
输出结果:

python全角和半角之间的转换