中文文本中可能出现的标点符号来源比较复杂,经过匹配等手段对他们处理的时候须要格外当心,防止遗漏。如下为在下处理中文标点的时候采用的两种方法,若有更好的工具,请推荐补充。php
!?。"#$%&'()*+,-/:;<=>@[\]^_`{|}~⦅⦆「」、、〃》「」『』【】〔〕〖〗〘〙〚〛〜〝〞〟〰〾〿–—‘’‛“”„‟…‧﹏.
zhon.hanzi.punctuation
函数便可获得这些中文标点。string.punctuation
函数可获得: !"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~
>>> import re >>> from zhon.hanzo import punctuation >>> line = "测试。。去除标点。。" >>> print re.sub(ur"[%s]+" %punctuation, "", line.decode("utf-8")) # 须要将str转换为unicode 测试去除标点 >>> print re.sub(ur"[%s]+" %punctuation, "", line) #将不会发生替换 测试。。去除标点。。
固然,若是想去除重复的符号而只保留一个,那么能够用\1
指明:好比python
>>> re.sub(ur"([%s])+" %punctuation, r"\1", line.decode("utf-8"))
若是不是用的zhon包提供的已是unicode码的标点集,而是本身定义,那么请不要忘了转换成unicode码:网络
punc = "!?。"#$%&'()*+,-/:;<=>@[\]^_`{|}~⦅⦆「」、、〃》「」『』【】〔〕〖〗〘〙〚〛〜〝〞〟〰〾〿–—‘’‛“”„‟…‧﹏." punc = punc.decode("utf-8")
Basic Latin: u'\u0020' - u'\007f' general punctuation: u'\u2000' - u'\u206f' CJK Symbols and Punctuation: u'\u3000' - u'\u303f' halfwidth and fulllwidth forms: u'\uff00' - u'\uffef'
在用u'\u0020-\u007f\u2000-\u206f\u3000-\u303f\uff00-uffef'
替换punctuation
就能实现上述操做。
PS:中文经常使用字符的范围是u'\u4e00' - u'\u9fff'
。匹配因此中文能够这样:函数
re.findall(ur"\u4e00-\u9fff", line)
小结:工具
参考:测试