NLP文本清理时常用的python小函数

1 # coding = utf-8
2 import re

1. 清理杂七杂八字符

 1 '''
 2 [a-zA-Z0-9] 字母数字
 3 [u4e00-u9fa5] 汉字的utf-8 code范围
 4 '''
 5 # 保留字母、数字、汉字和标点符号(),.!?":
 6 def remove_others(s):    
 7     return re.sub(r'[^a-zA-Z0-9u4e00-u9fa5(),.!?":]', ' ', s)
 8 
 9 # 删除多余的空白(including spaces, tabs, line breaks)'''
10 def remove_whitespaces(s):
11     return re.sub(r's{2,}', ' ', s)

2. 社交媒体文本中清除 @其他人

 1 def remove_atpeople(s):
 2     '''删除文本中@与其后面第一个空格之间的内容'''
 3     s = re.sub(r'@', ' @', s)
 4     s = re.sub(r':', ': ', s)
 5     ls = s.split()
 6     nls = []
 7     for t in ls:
 8         if t[0] == '@':
 9             continue
10         else:
11             nls.append(t) 
12 
13     return ' '.join(nls)
原文地址:https://www.cnblogs.com/wxiaoli/p/11600004.html