Python刪除一句話中的文字、符號、標點

簡單利用了正則表達式以及Python函數,去掉自己需要測試文本中的數字,文字以及標點符號。這個功能是用在一句中文文本分詞處理的基礎上,所以直接上一個分詞函數,包含了標點等處理的代碼:
from string import punctuation 
import re
import jieba
add_punc=',。、【】“”:;()《》‘’{}?!⑦()、%^>℃:.”“^-——=擅長於的&#@¥'
all_punc=punctuation+add_punc
def sentence_cut(x):#cut words and delete punctuation
    x=re.sub(r'[A-Za-z0-9]|/d+','',x)#delet numbers and letters
    testline = jieba.cut(x,cut_all=False)
    testline=' '.join(testline)
    testline=testline.split(' ')
    te2=[]
    for i in testline:
        te2.append(i)
        if i in all_punc:
            te2.remove(i)
    return te2

所以測試一下,效果還是不錯滴。注意,在Python中re模塊裏的punctuation只是包含了英文的特殊標點符號,所以如果要translate.punctuation是需要把這個punctuation·字符串再加上一些你需要的特殊字符等替換一下的。

 x='Python和它你選哪1個,你不要%任性地*操作'

sentence_cut(x)
Out[99]: ['和', '它', '你', '選', '哪個', '你', '不要', '任性', '地', '操作']
在網上看到其他大神的寫法,就是如果涉及的文本的處理中,只需要中文,那麼就只提取中文這樣簡單粗暴就好:
text=''.join(re.findall(u'[\u4e00-\u9fff]+', text))
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章