ABOUT ME

개발하는 도시 디자이너입니다.

Today
Yesterday
Total
  • [Python / re] 문자열 패턴 파악 후 데이터 프레임화 & 정규표현식 re이용한 문자열 치환하기
    python 데이터 전처리 2024. 4. 17. 15:17

    re package 설명

    : 간단하게 말하자면, 패턴이 있는 문자열을 다루는 패키지이다.

     

     

    정규표현식 re.sub()

    python 정규표현식 활용에 사용하는 re 모듈의 함수이다.

    문자열에서 패턴에 맞는 부분을 다른 문자열로 대체하는 데 사용된다.

     

    re.sub(pattern, replace, text)

     

    이는 text 중에서 해당하는 부분을 replace 로 대체한다.

     

     

    사용 예시

    # 이메일 주소 형식을 간단한 형식으로 변경
    email_text = "Contact me at example@mail.com for more information."
    modified_email = re.sub(r'\w+@\w+\.\w+', 'email', email_text)
    
    print(modified_email)
    
    # 결과
    >>> Contact me at email for more information.
    s = 'abc@naver.com, tpgudc@naver.com, abc@naver.com'
    
    result = re.sub(r'([a-z]+)@([a-z]+)\.com', 'new-address', s)
    
    result
    
    # 결과
    >>> 'new-address, new-address, new-address'

     

     

    re.match 사용예제

    import re
    
    # 원본 문자열
    row = '타입 : 325\n217.35/167.929㎡ (66평, 2세대)'
    
    # 패턴 정의: 각 정보를 그룹으로 캡처
    pattern = r'타입 : (\S+)\n(\d+\.\d+)/(\d+\.\d+)㎡ \((\d+)평, (\d+)세대\)'
    
    # 패턴 매칭
    match = re.match(pattern, row)
    
    # 조건 검사 및 JSON 출력
    if match:
        # 패턴에서 추출된 데이터
        type_code, area1, area2, pyeong, families = match.groups()
        
        # 조건 검사: 타입 325, 면적이 '217.35/167.929㎡ (66평)'인 경우
        if type_code != '-':
            house_type = '임대'
        else:
            house_type = ''
        if float(area2) > 60:
            house_area = '60 이상'
        else:
            house_area = '60 이하'
        families = int(families)
            
        
        output = {"임대": house_type, "house_area": house_area ,"families": families}
        print(output)
        output2 = {house_type +" " + house_area: families,}
        print(output2)
    else:
        print("패턴 매칭 실패")
        
    >>> {'임대': '임대', 'house_area': '60 이상', 'families': 2}
    >>> {'임대 60 이상': 2}

     

     

     

    re.split

    re.split(pattern, string, maxsplit=0, flags=0)

     

    string을 pattern으로 나눕니다. pattern에서 포착하는 괄호가 사용되면 패턴의 모든 그룹 텍스트도 결과 리스트의 일부로 반환됩니다. maxsplit이 0이 아니면, 최대 maxsplit 분할이 발생하고, 나머지 문자열이 리스트의 마지막 요소로 반환됩니다.

     

     

     

    re.split(r'\W+', 'Words, words, words.')
    # 결과 >>>['Words', 'words', 'words', '']

     

     

     

     

    공식문서 링크

     

    re — Regular expression operations

    Source code: Lib/re/ This module provides regular expression matching operations similar to those found in Perl. Both patterns and strings to be searched can be Unicode strings ( str) as well as 8-...

    docs.python.org

     

Designed by Tistory.