使用Python的translate函数处理(替换)字符和中文标点

使用Translate函数

Python3中的translate函数与Python2中已经不同了,使用Python3的方法如下.

maketrans(table,[deletion],[toNone])函数是在处理字符串str的时候,将其中的table中指定的字符一一对应映射成deletion中指定的字符,将toNone中指定的字符映射成None(即None).

例如:

1
2
3
4
5
import string
# string.punctuation中包含了常用的英文标点符号
translator = str.maketrans(dict.fromkeys(string.punctuation))
s = 'string with "punctuation" inside of it! Does this work? I hope so.'
print(s.translate(translator))


输出结果应该为:
1
sdring widh puncduadion inside of id Does dhis work I hope so

以上输出结果表明,translate函数是将给定的table对应的字符替换为deletion中的字符;将toNone中的字符替换为None.

而如果字符串中包含中文的时候,则需要对中文做一些特殊处理。

使用中文标点

可以使用名为zhon的包来获取常用中文字符, 安装:

1
pip3 install zhon

使用zhon

1
from zhon.hanzi import punctuation as ch_punctuation

只需将英文的string.punctuation替换为ch_punctuation即可,其他处理方法与英文相同。