python_note
  • Introduction
  • My Python
    • Anaconda
    • argparse
    • datetime
    • json
    • logging
    • numpy
    • open
    • openCC
    • pandas & csv
    • Socket & SocketServer
    • re
    • yaml
    • smtp
    • 物件操作
    • unittest
    • 線程
    • prettytable
    • IO
    • pycurl
    • sys
    • pickle
    • auto-python-to-exe
    • cython
    • nuitka
  • Crawler
    • Urllib & Requests
      • User-agent
      • Percent-Encoding
      • mail code
    • Selenium
    • TCP & UDP
    • 控制字符(control character)
  • Web Development
    • Flask
      • RESTful api
      • Template
      • blueprint
    • Django
      • 環境佈署(windows)
    • 檢查Port
    • Apache
    • 使用者行為
    • jQuery
    • 壓力測試
    • DataTable
    • Bootstrap
    • CSS
    • JavaScript
    • Chart.js
  • Deep Learning
    • Keras 設定
    • RNN
    • LSTM
  • Test
    • T-Test
  • 資料結構
    • Hash
    • 時間複雜度
  • NLP
    • N-gram
    • CKIP
    • 中文轉數字
    • CRF
    • Mutual Information
    • 模糊比對
  • Linebot
    • Heroku
    • 圖文選單
    • channel
  • Linux
    • 常用指令
    • shell script
    • sshfs
    • ssh
    • nodejs & npm
    • debug
  • GCP
    • app engine
    • ssh(gcp)
    • gsutil
    • brabrabra
    • Load Balancer
    • k8s
  • Database
    • mysql
    • elasticsearch
      • Query
      • Backup and Restore
      • elasticdump
      • es2csv
      • ELK
    • mongodb
      • install
      • authentication
      • pymongo
    • sql server
  • go
    • Swarm
  • Docker
    • Kitematic
    • Dockerfile
    • Swarm
  • Git
  • 其他
    • USB軟體保護
    • Windows效能監視器
  • Blockchain
Powered by GitBook
On this page
  • re
  • 檢查控制符號內容

Was this helpful?

  1. Crawler

控制字符(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))
PreviousTCP & UDPNextWeb Development

Last updated 5 years ago

Was this helpful?

參考資料:

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