處理(移除)unicode中標點符號

上學期修課final project自己抓了PTT的資料隨便玩,斷詞的時候先想把各式各樣的符號先去乾淨,看了這篇就知道translate是最快的方法。

但是要怎麼中文資料裡面各種Unicode的符號怎處理也是查了一下才知道怎麼做。重點是要做出符號對應的table(一個dictionary),下面例子我是將unicode中的標點符號都換成空白,以下分別是Python3跟2的做法:

Python3

1
2
3
4
5
6
7
8
9
10
import sys
import unicodedata

s = '您好!嗎?'

table = {c: ' ' for c in range(sys.maxunicode)
if unicodedata.category(chr(c)).startswith('P')}

result = s.translate(table)
print(result)

輸出:

1
您好 嗎

Python2

Python2用unicode稍微囉唆一點

1
2
3
4
5
6
7
8
9
10
11

import sys
import unicodedata

s = u'您好!嗎?'

table = {c: u' ' for c in range(sys.maxunicode)
if unicodedata.category(unichr(c)).startswith('P')}

result = s.translate(table)
print result

輸出:

1
您好 嗎

兩段code寫成function的gist

https://gist.github.com/jkw552403/3f2b1804d37cff1cfb7d

https://gist.github.com/jkw552403/2cb505fd4bc3c032ceba

Reference:

http://stackoverflow.com/questions/265960/best-way-to-strip-punctuation-from-a-string-in-python?rq=1