[Python]문자열 split 사용예제

split 함수를 사용하여, 문자열을 “공백과 콤마(,)”로 자르는 예제를 알아보자

# 방법1
def cnt_word1(filepath):
    with open(filepath, 'r') as file:
        txt = file.read()
    txt = txt.replace(",", " ")    
    txt_list = txt.split(" ")    
    return len(txt_list)

print(f'ex1 결과 : {cnt_word1("../source/22-1.txt")}')


# 방법2
import re

def cnt_word2(filepath):
    with open(filepath, 'r') as file:
        txt = file.read()
    
    # 정규표현식 사용
    txt_list = re.split(" |,", txt)    
    return len(txt_list)

print(f'ex2 결과 : {cnt_word1("../source/22-1.txt")}')


## 결과
ex1 결과 : 72
ex2 결과 : 72

You may also like...

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다