python基础之将中文标点符号转为英文标点符号

方法一:

对于有明确需求的转换,使用translate要更简单一些,它不需要你说的正则表达式,代码如下:

# In Python3, use str.maketrans instead(皆可)
# table里对应写出你需要转换成的转台 比如:()==> ()
table = {ord(f):ord(t) for f,t in zip(
     u',。!?【】()%#@&1234567890',
     u',.!?[]()%#@&1234567890')}

# 需要转换的文本
t = u'中国,中文,标点符号!你好?12345@#【】+=-()'

t2 = t.translate(table)

'''
print(t2)
中国,中文,标点符号!你好?12345@#[]+=-()
'''

推荐。

方法二:

import unicodedata

t = u'中国,中文,标点符号!你好?12345@#【】+=-()'

t2 = unicodedata.normalize('NFKC', t)

'''
print t2
中国,中文,标点符号!你好?12345@#【】+=-()
'''

unicode有个normalize的过程,按照unicode标准,有C、D、KC、KD四种,KC会将大部分的中文标点符号转化为对应的英文,还会将全角字符转化为相应的半角字符。

转载请注明转自:https://blog.csdn.net/Owen_goodman/article/details/107783304

你可能感兴趣的:(Python,python)