查看文本,替换文本
思路:处理从网络中下载的数据,我们往往会碰到一些特殊字符('\u200b|\u200c|\u200d|\xa0'
),这些字符无实际意义,我们在处理的过程中,首先先按照字符char统计一下,然后观察并将其用正则去除。
#使用conter()查看特殊字符。
from collections import Counter
cot=Counter()
for x in tqdm(df['body']):
for s in x:
cot.update(s)
print(sorted(cot.keys()))
['\t', '\n', ' ', '!', '"', '#', '$', '%', '&', ……,'\ufff0', '', '�', '🇷', '🇺', '🌟',]
#使用正则替换将特殊字符替换
import re
s='\u200bक्या \u200cबाइडन भारत के लिए ट्रंप से बेहतर साबित \xa0होंगे?'
re.sub(r'\u200b|\u200c|\u200d|\xa0',' ',s)
' क्या बाइडन भारत के लिए ट्रंप से बेहतर साबित होंगे?'
def sub_specialspecial1(s):
#特殊字符串替换,
pattern1=re.compile('[\x8b-\xbd]') #
pattern2=re.compile('[\u2002-\uffff]')
pattern3=re.compile(r'🇷🇺🌟🌸🎀🎥🏆👉💜💪😉😍🙃🙌🙏🦄')
s=pattern3.sub(' ',pattern2.sub(' ',pattern1.sub(' ',s)))
# ?> 前后添加空格
s=re.sub(r'([\u0021-\u0040]|[\u007b-\u007e])',r' \1 ',s)
s=re.sub('( ){2,}|\t|\n',' ',s)
s=re.sub('( ){2,}|\t|\n',' ',s)
return s
编码有关的内容
- 查看文本的utf-8编码
fu=lambda x : x.encode('unicode_escape').decode()
fu('故')
2.字符转ascii数字ord()
3. 数字转字符chr()
正则表达式(复习笔记 —面试用)
定位文本的位置
正则表达的两大功能
- 搜索(有就行)
- 匹配(完全一致)