2024-05-27-MON 1-5교시
import re
# 1.정규표현식 패턴 객체를 생성
reg = re.compile('\d\d\d-\d\d\d-\d\d\d\d')
# 2.메소드를 통해서 문자열에서 패턴에 매칭되는 문자열을 찾아내거나 수정
mo = reg.search('My number in 415-555-2323') #search는 첫번째만 가져옴/ findall은 전부 가져옴
mo.group()
\d : 숫자
\s : 빈칸, 탭, 줄바꿈
\w : 문자, 숫자, 밑줄(언더바_)
\D : 숫자가 아닌 문자
\S : 빈칸, 탭, 줄바꿈이 아닌 문자
\S : 문자, 숫자, 밑줄이 아닌 문자
1) ? : 0번 or 1번
2) * : 0번이상 반복
3) + : 1번 이상 반복
4) {n} n번 반복
5) {n,m} n번부터 m번까지 반복(,랑 m사이 띄어쓰기 있으면 실행 안됨)
[] : 사용자 정의 정규표현식
[aeiouAEIOU] : 모음
[a-zA-Z] :알파벳
[0-9] : 숫자
[a-zA-Z0-9] : 알파벳 혹은 숫자
[^patter] : patter이 아닌 문자
1. Search()
- 매칭이 되는 첫번째 문자열 리턴
reg = re.compile('Batman|Tina Fey')
# |는 or를 뜻하므로 batman이나 Tina를 찾는다.
mo = reg.search("Batman and Tina Fey is a movie")
mo.group()
reg = re.compile('Bat(wo)?man')
# ?는 앞에 정의된 (wo)패턴이 1번 또는 0번 반복된 패턴을 찾는다 //없으면 오류
mo = reg.search("The Adventures of Batman")
mo.group()
reg = re.compile('Bat(wo)+man')
# +는 앞에 정의된(wo)패턴이 1번이상
# 등장하는 패턴을 찾는다.
# 없으면 오류
mo = reg.search("The Adventures of Batwoman")
mo.group()
reg = re.compile('Bat(wo)*man')
# *은 +와 같지만 0번도 가능하다
mo = reg.search("The Adventures of Batwoman")
mo.group()
reg = re.compile('Bat(wo){2}man')
# {n}은 (wo)패턴이 n번 정의된 패턴을 찾는다
mo = reg.search("The Adventures of Batwowoman")
mo.group()
reg = re.compile('Bat(wo){2,4}man')
# {n,m}은 (wo)패턴이 n번부터 m번까지
# 정의된 패턴을 찾는다.
mo = reg.search("The Adventures of Batwowowoman")
mo.group()
<정리>
2. findall()
reg = re.compile('\d\d\d-\d\d\d-\d\d\d\d')
reg.findall('my number is 214-874-8965 and your number is 287-845-8956')
reg = re.compile('\d+\s\w+')
# (숫자가한번이상, 스페이스, 문자한번이상)
reg.findall('12 drums, 11 pipers, 10 lords, 0 ladies, 8 maid, 7 swans')
reg = re.compile('[aeiouAEIOU]')
reg.findall('RoboCop eats baby food BABY FOOD.')
reg = re.compile('[^aeiouAEIOU]')
reg.findall('RoboCop eats baby food BABY FOOD.')
reg = re.compile('^Hello')
#문자열 시작에 나오는 Hello를 의미
reg.findall('Hello world Hello')
#끝의 Hello는 안나옴
reg =re.compile('\d+$')
reg.findall('your number55 is 430')
3. sub('정규표현식 패턴', '새로운 문자열', text)
- text에서 '정규표현식 패턴' 찾아서 '새로운 문자열'로 바꾼다.
re.sub('Agent \w+', 'Censored', 'Agent Alice gave the secret documents to Agent Bob')
reg = re.compile('Agent \w+')
reg.sub('Censored', 'Agent Alice gave the secret documents to Agent Bob' )
4. match()
^ : 문자열 시작
$ : 문자열 끝
reg = re.compile('\d+$')
m = reg.match('Your number55 is sssew')
print(type(m))
if m :
print('매칭이 되는 패턴이 있습니다')
else:
print('매칭이 되는 패턴이 없습니다')
# 이메일 추출
text = '저의 이메일은 pine@hanmail.net이고, 담당자 이메일은 fio@gmail.com입니다.'
email = re.compile('[a-zA-Z0-9]+@[a-zA-Z0-9]+.[a-z]+')
email.findall(text)
# 금액만 추출
text = '총 금액은 122330.6원 입니다. 세금은 5214.233원 입니다'
#price = re.compile('[0-9]+.[0-9]+\w')
price = re.compile('\d+.\d+원')
price.findall(text)
# 날짜만 추출
text = '계약날짜는 2015년 2월 15일, 계약 종료일은 2017년 06월 22일입니다.'
#day = re.compile('\d\d\d\d년\s\d+월\s\d+일')
day = re.compile('\d+년\s\d+월\s\d+일')
day.findall(text)
#url을 추출
text = '''저의 홈페이지 주소는 https://www.naver.com 입니다. 당신의 홈페이지 주소는 https://cafe.daum.net입니다.'''
url = re.compile('[a-z]+://[a-z]+.[a-z]+.[a-z]+')
url.findall(text)
#url을 비인식 ***로 바꾸기
text = '''저의 홈페이지 주소는 https://www.naver.com 입니다. 당신의 홈페이지 주소는 https://cafe.daum.net입니다.'''
url = re.compile('[a-z]+://[a-z]+.[a-z]+.[a-z]+')
url.sub('*****',text)
1-5교시 : 파이썬 마무리
6-8교시 : 크롤링