티스토리 뷰

.search()

패턴 매칭한 결과를 re.Match로 돌려줍니다.

import re
pattern = "\[가-힣\]\[0-9\]{1,3}:\[0-9\]{1,3} "
r = re.search(pattern, line).group(0)
print(type(r), r)

 

.findall() - 모두 찾기

패턴에 매칭되는 모든 문자열을 찾아서 list로 리턴함

r = re.compile('[가-힣]{1,2}').findall('김5:5')
r2 = re.compile('[0-9].+').findall('김5:5')
print(type(r), r)
print(type(r2), r2)

결과

<class 'list'> ['김']
<class 'list'> ['5:5']

 

.sub() - 찾아서 바꾸기 혹은 지우기

hello - aoeu를 hello*aoeu로 바꾼다. 지울려면 ""로 해주면 지워짐

import re

pattern = re.compile(" - ")
result = pattern.sub( "*","hello - aoeu")
print(result)

결과

hello*aoeu

 

자주 쓰는 식

>HQ380231\n

^\>.+\n$
>로 시작하고 \n로 끝나는 줄을 찾는다.
@\b[A-Z][A-Z]+\b
@로 시작하고 대문자로만 이루어진 문자열

\t\n replace하기

import re
value = re.sub("(\n|\t)","",div_td.text)

regexr (\n|\t)를 이용하는 방법

태그 안에 또 태그가 있는 경우 text만 뽑아내기

<a href="javascript:view('20200113000000001388','grid');">
                                        국가품종목록 등재품종 목록<span class="tit_info">국립종자원_국가품종목록 등재 내역</span>
</a>

위와 같이 atag안에 텍스트가 들어있지만 따로 분류가 되어 있지 않고 그 안에 또 tag가 있는 경우

def get_row(tr):
    tds = tr.find_all('td')
    atag = str(tds[0].find('a')).split('<span class="tit_info">')
    first = re.compile('\t.*\t').sub('', atag[0]).split('\n')[1]
    second = atag[1].split('</span>')[0]
    print(first)
    print(second)

a를 찾아서 string으로 바꾼 후 span을 가지고 split을 했다.

'<span class="tit_info">'

tab이 있는 경우는 아래와 같이 \t를 이용했다.

'\t.*\t'

 

 

패턴을 매칭한것과, 그것을 없앤것

import re

pattern = "\[가-힣\]\[0-9\]{1,3}:\[0-9\]{1,3} "

index = re.search(pattern, line).group(0)

replaced = re.sub(pattern, "", line)

로그를 분석 할 때 로그에 여러개의 로그가 쌓여서 내가 필요한것만 보고 싶을 때 로그가 35메가라면 눈으로 보기는 힘들다

그래서 이 코드를 만들었다.

일단 re를 import해줘야 함.

import re
fileLocation = "C:/Users/kyeongrok.kim/Desktop/"
fileName = "parse_2017-06-05.23.log"
targetFileName = "helllo.txt"
pattern = '.*1703427.*'

class LogParser:
    def extractPattern(self, sFileLocation="C:/Users/kyeongrok.kim/Desktop/", sTargetFileName = "hello.txt", sPattern = "1234"):
        with open(sFileLocation + fileName, mode="rt", encoding='utf-8') as f:
            string = f.read()

        pattern = re.compile(sPattern)
        findAll = pattern.findall(string)

        for item in findAll:
            with open(sFileLocation + sTargetFileName, mode="w+", encoding='utf-8') as f:
                f.write(item)

        print("success")


parser = LogParser()
parser.extractPattern(fileLocation, targetFileName, pattern)

위 코드를 사용하면 from파일에서 특정 패턴을 추출해서 targetFile로 추출한 패턴의 데이터만 뽑아낼 수 있다.

패턴 매칭 해서 찾아주는 함수

import re

def getMatchedText(pattern, text):  
    matches = re.findall(pattern, text)  
    result = \[\]  
    for match in matches:  
        result.append(match)  
    return result

end.

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
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
글 보관함