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

Was this helpful?

  1. My Python

re

PreviousSocket & SocketServerNextyaml

Last updated 5 years ago

Was this helpful?

#簡易搜尋範例
import re

test = 'hello re!!!' #要被檢查的句子
pattern = re.compile(r'.{1}re.{1}') #搜尋條件:尋找re並包含前後一個任意字元

match = pattern.search(test)
if match: #找不到則為None
    print(match.group()) #輸出結果: re!(包含前一個空格)


#簡易取代範例
pattern2 = re.compile(r're') #條件:找到re
print(pattern2.sub('RE',test)) #將字串中的re取代為RE,輸出結果:hello RE!!!

爬蟲應用:剔除文章的html標籤

import re

def remove_html_tags(data): #data為網頁原始碼
    p = re.compile(r'<.*?>')
    return p.sub('', data)

test = '<h1>123</h2>'
print(remove_html_tags(test)) #輸出結果:123

語料處理應用:

import re

test='今天天氣很好,覺得肚子很餓,粗乃玩'
pattern=re.compile(r',.*肚子.*,') #包含肚子的一句話
result=pattern.search(test)

print(result.group()) #搜尋結果:,覺得肚子很餓,

判斷語言種類:

import re

test=u'abc找中文abc'
pattern=re.compile(u'[\u4e00-\u9fa5]+') #'+':一個或多個,找到一個或多個中文字
result=pattern.search(test)

print(result.group()) #搜尋結果:找中文

字串與pattern需要是相同編碼

擷取斷詞結果詞性

#python3
import re

test='a3(neu) sss(Neu) ((PARENTHESISCATEGORY) )(PARENTHESISCATEGORY)' #假設斷詞結果
pattern=re.compile(r'\([a-z,A-Z,_,0-9]+\)') #加斜線就可連同括弧一起比對

match =pattern.findall(test)
match2=pattern.search(test)

print(match)         #['(neu)', '(Neu)', '(PARENTHESISCATEGORY)', '(PARENTHESISCATEGORY)']  如果找不到則回傳空陣列
print(match2.group())#(neu)   只會找第一個

使用特定符號分隔

#python3
import re
raw='123\n456。789'
sentences=re.split('\n|。', raw)

print(sentences) #['123', '456', '789']

raw2='123\n456\n789' #只出現斷行符號
sentences2=re.split('\n|。', raw)

print(sentences2) #['123', '456', '789']

尋找url

# 找圖片
raw_content = "test content"
urls = re.findall('(?:http\:|https\:)?\/\/.*\.(?:png|jpg)', raw_content)

# 找url
all_url = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\), ]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', raw_article)

讀取所有查詢結果的indx位置

import re
term_pat = re.compile(r'(<FRONT>)([.\n\w\W]*?)(<END>)')
get_term = term_pat.finditer(sttr_replace)

# 將計算結過存入字典
for idx, term in enumerate(get_term):
    # print(term)
    start = term.start()
    end = term.end()
    print(term, start, end)


# solution 2
iter = re.finditer(r"\bis\b", String)
indices = [m.start(0) for m in iter]

過濾特殊字符

有些在控制字符中

簡易範例
https://stackoverflow.com/questions/40813850/python-2-7-regex-for-image-url
https://www.geeksforgeeks.org/python-check-url-string/
https://stackoverflow.com/questions/3519565/find-the-indexes-of-all-regex-matches
https://stackoverflow.com/questions/2674391/python-locating-the-position-of-a-regex-match-in-a-string/16360404
https://blog.csdn.net/jlulxg/article/details/84650683
符號資訊
完整教學
https://docs.python.org/2/library/re.html