Computer >> 컴퓨터 >  >> 프로그래밍 >> Python

파이썬으로 문자열의 단어 개수 세기: for문·while문·함수 3가지 방법

문자열이 주어졌을 때 전체 단어가 몇 개인지, 혹은 특정 단어가 몇 번 등장하는지 확인해야 하는 경우가 자주 있습니다. 이번 글에서는 파이썬(Python)을 이용해 입력받은 문자열의 단어 개수를 세고 그 결과를 출력하는 여러 가지 방법을 예제 코드와 함께 소개합니다.

방법 1: for 반복문 사용

문자열을 한 글자씩 순회하면서 공백(' '), 줄바꿈(\n), 탭(\t) 같은 구분자를 만날 때마다 카운트를 1씩 증가시키는 방식입니다. 초기값을 1로 설정하는 이유는 마지막 단어 뒤에는 공백이 없기 때문입니다.

test_string = input("String to search is : ")
total = 1

for i in range(len(test_string)):
    if(test_string[i] == ' ' or test_string[i] == '\n' or test_string[i] == '\t'):
        total = total + 1

print("Total Number of Words in our input string is: ", total)

실행 결과

String to search is : Python is a high level language. Python is interpreted language. Python is general-purpose programming language
Total Number of Words in our input string is: 16

방법 2: while 반복문 사용

for 문 대신 while 문으로 인덱스를 직접 하나씩 증가시키면서 동일한 로직을 구현할 수도 있습니다.

test_string = input("String to search is : ")
total = 1
i = 0

while(i < len(test_string)):
    if(test_string[i] == ' ' or test_string[i] == '\n' or test_string[i] == '\t'):
        total = total + 1
    i += 1

print("Total Number of Words in our input string is: ", total)

실행 결과

String to search is : Python is a high level language. Python is interpreted language. Python is general-purpose programming language
Total Number of Words in our input string is: 16

방법 3: 함수로 구현하기

단어 개수를 세는 로직을 별도의 함수로 분리하면 코드의 재사용성과 가독성이 크게 향상됩니다.

def count_words(test_string):
    word_count = 1
    for i in range(len(test_string)):
        if(test_string[i] == ' ' or test_string[i] == '\n' or test_string[i] == '\t'):
            word_count += 1
    return word_count

test_string = input("String to search is :")
total = count_words(test_string)
print("Total Number of Words in our input string is: ", total)

실행 결과

String to search is :Python is a high level language. Python is interpreted language. Python is general-purpose programming language
Total Number of Words in our input string is: 16

보너스: split() 메서드로 더 간단하게

사실 파이썬에서는 split() 메서드를 활용하면 단어 개수를 한 줄로 셀 수 있습니다. split()은 인자 없이 호출할 경우 연속된 공백, 탭, 줄바꿈까지 모두 처리해 주므로 위 방법들보다 간결하고 안전합니다.

test_string = input("String to search is : ")
word_count = len(test_string.split())
print("Total Number of Words in our input string is: ", word_count)

지금까지 for 반복문, while 반복문, 사용자 정의 함수, 그리고 split() 메서드까지 다양한 방식으로 문자열의 단어 개수를 세는 방법을 살펴보았습니다. 학습 목적이라면 반복문 방식으로 로직을 익히고, 실무에서는 split() 메서드를 활용하는 것을 추천합니다.