Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

히바리 쿄야 와 함께 하는 Developer Cafe

[5일차] DO IT 점프 투 파이썬/p269~p320/게시판 페이징, 정규표현식 본문

Python

[5일차] DO IT 점프 투 파이썬/p269~p320/게시판 페이징, 정규표현식

TWICE&GFRIEND 2021. 2. 22. 19:02
def GuGu(n):
    result = []
    result.append(n*1)
    result.append(n*2)
    result.append(n*3)
    result.append(n*4)
    result.append(n*5)
    result.append(n*6)
    result.append(n*7)
    result.append(n*8)
    result.append(n*9)
    return result


print(GuGu(2))
[2, 4, 6, 8, 10, 12, 14, 16, 18]

i = 1

while i < 10:
    print(i)
    i+=1
    
1
2
3
4
5
6
7
8
9


def GuGu(n):
    result = []
    i = 1
    while i < 10:
        result.append(n * i)
        i = i + 1
    return result
    

print(GuGu(2))
[2, 4, 6, 8, 10, 12, 14, 16, 18]




3의 배수 5의 배수 합하기

result = 0

for n in range(1, 1000):
    if n % 3 or n % 5 == 0:
        result += n
        
print(result)
365832



게시판 페이징 실습

총페이지수 = (총 건수 / 한 페이지당 보여줄 건수) + 1

def getTotalPage(m, n):
    return m // n + 1
    

print(getTotalPage(5,10))
1

print(getTotalPage(15,10))
2

print(getTotalPage(25,10))
3

print(getTotalPage(30,10))
4

def getTotalPage(m, n):
    if m % n == 0:
        return m // n
    else:
        return m // n + 1
        

print(getTotalPage(5,10))
1

print(getTotalPage(15,10))
2

print(getTotalPage(25,10))
3

print(getTotalPage(30,10))
3


메모장 만들기

import sys

option = sys.argv[1]
memo = sys.argv[2]

print(option)
print(memo)

D:\Python>python memo.py -a "Lift is too short"
-a
Lift is too short


D:\Python>python memo.py -a "Lift is too short"

D:\Python>python memo.py -a "You need python"

D:\Python>type memo.txt
Lift is too short
You need python


D:\Python>python memo.py -v
Lift is too short
You need python


D:\Python>python tabto4.py a.txt b.txt
a.txt
b.txt
Life      is          too    short
You      need     python

D:\Python>python tabto4.py a.txt b.txt
a.txt
b.txt


import os

def search(dirname):
    try:
        filenames = os.listdir(dirname)
        for filename in filenames:
            full_filename = os.path.join(dirname,filename)
        if os.path.isdir(full_filename):
            search(full_filename)
        else:
            ext = os.path.splitext(full_filename)[-1]
            if ext == '.py':
                print(full_filename)
    except PermissionError:
        pass
            
    
search("D:/")



 

정규 표현식

\d  숫자와 매치 [0~9]와 동일한 표현식
\D  숫자와 아닌것과 매치 [^0-9]와 동일한 표현식
\s  whitespace문자 (space나 tab 처럼 공백을 표현하는 문자) 와 매치
[\t\n\r\f\v] 와 동일한 표현식 맨 앞의 빈칸은 공백 문자(space)를 의미한다.
\S  whitespace 문자가 아닌 것과 매치 [^ \t\n\r\f\v ] 와 동일한 표현식
\w  문자 + 숫자 와 매치 [a-zA-Z0-9_] 와 동일한 표현식
\W  문자 + 숫자 가 아닌 문자와 매치, [^a-zA-Z0-9_] 와 동일한 표현식


Dot(.) 줄바꿈 문자인 \n을 제외한 모든 문자와 매치

a.b  a와 b 사이에 줄바꿈 문자를 제외한 어떤 문자가 들어와도 모두 매치
"a + 모든 문자 + b"

a[.]b   a와b 사이에 Dot(.) 문자가 있으면 배치

반복(*) 
ca*t   문자 바로 앞에 있는 a가 0번 이상 반복되면 매치

반복(+) 최소 1번 이상 반복 될때 사용

ca+t   a가 1번 이상 반복되면 매치


({m,n},?)

{m} ca{2}t  a가 2번 반복되면 매치

{n,m}  ca{2,5}t  a가 2~5번 반복되면 매치한다


?  ab?c  b가 0~1번 사용되면 매치 



메서드

match()   문자열의 처음부터 정규식과 매치되는지 조사
search()  문자열 전체를 검색하여 정규식과 매치되는지 조사
findall()  정규식과 매치되는 모든 문자열(substring)을 리스트로 돌려준다
finditer()  정규식과 매치되는 문자열(substring)을 반복 가능한 객체로 돌려준다.


import re

p = re.compile('ab*')

print(p)
re.compile('ab*')

import re

p = re.compile('[a-z]+')

print(p)
re.compile('[a-z]+')

m = p.match("python")

print(m)
<re.Match object; span=(0, 6), match='python'>


m = p.match("3 python")
문자 3이 [a-z]+ 정규식에 포함되지 않기 때문에 none
print(m)
None


m = p.search("python")

print(m)
<re.Match object; span=(0, 6), match='python'>

m = p.search("3 python")
문자열 전체를 검색하기 때문에 3이후의 파이썬 문자열과 매치
print(m)
<re.Match object; span=(2, 8), match='python'>


result = p.findall("i love you")

print(result)
['i', 'love', 'you']


result = p.finditer("i love you")

print(result)
<callable_iterator object at 0x000001BE69CA89C8>

for r in result: print(r)
<re.Match object; span=(0, 1), match='i'>
<re.Match object; span=(2, 6), match='love'>
<re.Match object; span=(7, 10), match='you'>

반복 가능한 객체로 반환


match 객체의 메서드

group()     매치된 문자열을 반환
start()     매치된 문자열의 시작 위치를 반환
end()       매치된 문자열의 끝 위치를 반환
span()      매치된 문자열의 (시작,끝)에 해당하는 튜플을 반환


import re

p = re.compile('[a-z]+')

m = p.match("python")

m.group()
Out[61]: 'python'

m.start()
Out[62]: 0

m.end()
Out[63]: 6

m.span()
Out[64]: (0, 6)




컴파일 옵션

DOTALL       S     dot 문자(.) 가 줄바꿈 문자를 포함하여 모든 문자와 매치
IGNORECASE   I       대 소문자에 관계없이 매치
MULTILINE    M       여러 줄과 매치된다 (^,$ 메타 문자의 사용과 관계없는 옵션)
VERBOSE      X       verbose 모드 사용 (정규식을 보기 편하게 할 수도 있고 주석 사용)


import re

p = re.compile('a.b')

m = p.match('a\nb')

print(m)
None

p = re.compile('a.b', re.DOTALL)

m = p.match('a\nb')

print(m)
<re.Match object; span=(0, 3), match='a\nb'>


p = re.compile('[a-z]',re.I)

p.match('python')
Out[75]: <re.Match object; span=(0, 1), match='p'>

p.match('Python')
Out[76]: <re.Match object; span=(0, 1), match='P'>

p.match('PYTHON')
Out[79]: <re.Match object; span=(0, 1), match='P'>


import re

p = re.compile("^python\s\w+")

data = """python one
life is too start
python two
you need python
python three"""

print(p.findall(data))
['python one']

p = re.compile("^python\s\w+", re.MULTILINE)

data = """python one
life is too start
python two
you need python
python three"""

print(p.findall(data))
['python one', 'python two', 'python three']




| 메타 문자는 or 과 동일한 의미로 사용  A 또는 B 라는 의미
p = re.compile('Crow|Servo')

m = p.match('CrowHello')

print(m)
<re.Match object; span=(0, 4), match='Crow'>

^ 메타문자는 문자열의 맨 처음과 일치함을 의미 
멀티라인을 사용할 경우 여러줄의 문자열일 때 각줄의 처음과 일치

print(re.search('^Life','Life is too short'))
<re.Match object; span=(0, 4), match='Life'>

print(re.search('^Life','My Life'))
None


$ 메타 문자는 ^ 메타 문자와 반대  문자열의 끝과 매치함을 의미

print(re.search('short$','Life is too short'))
<re.Match object; span=(12, 17), match='short'>

print(re.search('short$','Life is too short, you need python'))
None

\A 문자열의 처음과 매치  멀티라인 옵션 쓸때 줄과 상관없이 전체 문자열의 처음하고만 매치

\Z 문자열의 끝과 매치  멀티라인 옵션 전체 문자열의 끝과 매ㅣ

\b 단어 구분자 whitespace 에 구분 

p = re.compile(r'\bclass\b')

print(p.search('no class at all'))
<re.Match object; span=(3, 8), match='class'>

print(p.search('the declassified algorithm'))
None

print(p.search('one subclass is'))
None


\B  whitespace 로 구분된 단어가 아닌 경우에만 배치

p = re.compile(r'\Bclass\B')

print(p.search('no class at all'))
None

print(p.search('the declassified algorithm'))
<re.Match object; span=(6, 11), match='class'>

print(p.search('one subclass is'))
None


그루핑


p = re.compile(r"(\w+)\s+\d+[-]\d+[-]\d+")

m = p.search("jung 010-1234-1234")

print(m.group(1))
jung


group(0)          매치된 전체 문자열
group(1)          첫 번째 그룹에 해당하는 문자열
group(2)          두 번째 그룹에 해당하는 문자열
group(n)          n 번째 그룹에 해당하는 문자열


p = re.compile(r"(\w+)\s+(\d+[-]\d+[-]\d+)")

m = p.search("jung 010-1234-1234")

print(m.group(2))
010-1234-1234


p = re.compile(r"(\w+)\s+((\d+)[-]\d+[-]\d+)")

m = p.search("jung 010-1234-1234")

print(m.group(3))
010


그루핑 문자열 재참조


p = re.compile(r'(\b\w+)\s+\1')

p.search("Paris in the the spring").group()
Out[134]: 'the the'

재참조 메타문자 \1  정규식 그룹중 첫번째 그룹을 가리킴

p = re.compile(r"(?P<name>\w+)\s+((\d+)[-]\d+[-]\d+)")

m = p.search("jung 010-1234-1234")

print(m.group("name"))
jung

p = re.compile(r'(?P<word>\b\w+)\s+(?P=word)')

p.search('Paris in the the spring').group()
Out[139]: 'the the'


p = re.compile(".+:")

m = p.search("http://google.com")

print(m.group())
http:



(?=...)  긍정형 전방 탐색

... 에 해당하는 정규식과 매치되어야 하며 조건이 통과되어도 문자열이 소비되지 않음

(?!...)  부정형 전방 탐색

... 에 해당하는 정규식과 매치되지 않아야 하며 조건이 통과 되어도 문자열이 소비되지 않음


p = re.compile(".+(?=:)")

m = p.search("http://google.com")

print(m.group())
http




문자열 바꾸기

p = re.compile('(blue|white|red)')

p.sub('colour','blue socks and red shoes')
Out[148]: 'colour socks and colour shoes'

p.sub('colour','blue socks and red shoes', count=1)
Out[149]: 'colour socks and red shoes'


p = re.compile(r"(?P<name>\w+)\s+(?P<phone>(\d+)[-]\d+[-]\d+)")

print(p.sub("\g<phone>\g<name>","jung 010-1234-1234"))
010-1234-1234 jung

print(p.sub("\g<2>\g<1>","jung 010-1234-1234"))
010-1234-1234 jung


def hexrepl(match):
    value = int(match.group())
    return hex(value)
    

p = re.compile(r'\d+')

p.sub(hexrepl, 'Call 65490 for printing, 49152 for user code.')
Out[156]: 'Call 0xffd2 for printing, 0xc000 for user code.'

match 객체를 입력받아 16진수로 변환 



s = '<html><head><title>Title</title>'

len(s)
Out[158]: 32

print(re.match('<.*>',s).span())
(0, 32)

print(re.match('<.*>',s).group())
<html><head><title>Title</title>

print(re.match('<.*?>',s).group())
<html>






Comments