控制字符(control character)
看不到但確實存在的幽靈字符,可使用re進行替換,比replace來的方便些
re
# python3
import re
text = '你\u202a好阿\u202e陌生人' # 參雜控制字符
print(text, [text], len(text)) # 長度為8 (6+2)
# 將特定範圍的符號替換為空字串
str_input = re.sub(r'[\u200b-\u200f \u2029-\u202e \u2061-\u2064 \u206a-\u206f]', "", text)
print(str_input, [str_input], len(str_input)) # 長度為2
檢查控制符號內容
在python3可使用內建函數來查看字符編碼與內容
ord(str):回傳在unicode中的對應編號
chr(int):回傳編號所對應的unicode
目前遇到的幽靈字符範圍如下:
字符
編碼
"\u200b"~"\u200f"
8203~8207
"\u2029"~"\u202e"
8233~8239
"\u2061"~"\u2064"
8289~8292
"\u206a"~"\u206f"
8298~8303
# python3
# 輸出編碼與字符
for i in range(8000, 9000):
print(chr(i), ord(chr(i))) # 字符, 編碼
奇怪的空格
字符
編碼
"\u3000"
12288 (全形空格)
"\u202f"
8239
"\u205f"
8287
"\xa0"
160
替換空格
# python3
import re
text = '你\u202a\u202a好阿\u202e陌生\u202f人' # 參雜控制字符
print(text, [text], len(text)) # 長度為8 (6+2)
str_input = re.sub(r'[\u202f\u205f\u3000]', " ", text)
print(str_input, [str_input], len(str_input))
參考資料: https://www.itread01.com/article/1486433903.html https://dotblogs.com.tw/law1009/2013/07/13/109833 https://www.programcreek.com/python/example/144/re.VERBOSE
Last updated
Was this helpful?