字符編碼
為什么Python使用過程中會(huì)出現(xiàn)各式各樣的亂碼問題,明明是中文字符卻顯示成“/xe4/xb8/xad/xe6/x96/x87”的形式?為什么會(huì)報(bào)錯(cuò)“UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)”?本文就來研究一下這個(gè)問題。
字符串在Python內(nèi)部的表示是unicode編碼,因此,在做編碼轉(zhuǎn)換時(shí),通常需要以u(píng)nicode作為中間編碼,即先將其他編碼的字符串解碼(decode)成unicode,再從unicode編碼(encode)成另一種編碼。
decode的作用是將其他編碼的字符串轉(zhuǎn)換成unicode編碼,如str1.decode('gb2312'),表示將gb2312編碼的字符串str1轉(zhuǎn)換成unicode編碼。
encode的作用是將unicode編碼轉(zhuǎn)換成其他編碼的字符串,如str2.encode('gb2312'),表示將unicode編碼的字符串str2轉(zhuǎn)換成gb2312編碼。
因此,轉(zhuǎn)碼的時(shí)候一定要先搞明白,字符串str是什么編碼,然后decode成unicode,然后再encode成其他編碼
#!/usr/bin/env python
#coding=utf-8
s="中文"
if isinstance(s, unicode):
#s=u"中文"
print s.encode('gb2312')
else:
#s="中文"
print s.decode('utf-8').encode('gb2312')
原文:https://blog.csdn.net/lxdcyh/article/details/4018054
正則過濾emoji
import re
text = '??佛渡有緣人【引流】QQ:1099615807 微信:CL8887888/.,s,,,,,.。。。。????'
myre = re.compile(ur"[^A-Za-z0-9\s\r\t\n\u4e00-\u9fa5\uff08\u3008\u300a\u300c\u300e\ufe43\u3014\u2026\uff5e\uffe5\u3010\uff0c\uff1f\uff1a\u201c\u2018\uff09\u3009\u300b\u300d\u300f\ufe44\u3015\u2014\ufe4f\u3001\u3011\u3002\uff01\uff1b\u201d\u2019\[\]\(\){}\|\"\:<>~`!@#$%&*?,./:]")
cleanEmoji = myre.sub(u'[emoji]', text)
print cleanEmoji
// 輸出 [emoji][emoji]佛渡有緣人【引流】QQ:1099615807[emoji]微信:CL8887888/.,s,,,,,.。。。。
上面的例子用于存數(shù)據(jù)進(jìn)sqlite3數(shù)據(jù)庫時(shí)將emoji過濾,因?yàn)檎伊撕芫枚紱]找到將emoji存進(jìn)數(shù)據(jù)庫的方法,在其他數(shù)據(jù)庫可以將編碼格式換成utf-8mb4便可以存儲(chǔ)emoji。上面正則的意思是匹配 數(shù)字、字母、中文、中英文的標(biāo)點(diǎn)符號(hào) 以外的文本。
os操作
os.path.join(str1,str2) : 用于拼接兩個(gè)文件路徑,在windows下可以補(bǔ)齊 \,在Linux下自動(dòng)補(bǔ)齊/,這樣可以避免在不同操作系統(tǒng)環(huán)境下路徑不對(duì)的坑。
os.path.exists(path): 判斷該路徑是否存在,一般用來判斷文件是否存在
os.system: 執(zhí)行終端命令
os.remove: 刪除文件
os.removedirs: 刪除空的文件夾
# 刪除非空文件夾
import shutil
shutil.rmtree(path)