발전을 위한 기록

[Python] 파이썬으로 txt 파일 단어 수 세기 본문

프로그래밍/파이썬

[Python] 파이썬으로 txt 파일 단어 수 세기

릴릴2 2024. 1. 24. 03:11

파이썬을 이용하여 텍스트 파일의 단어 빈도수를 분석할 수 있습니다.

주석 없는 코드

def count_word_frequency(text):
    words = text.split()
    frequency = {}

    for word in words:
        word = word.lower().strip(",.!?")  
        frequency[word] = frequency.get(word, 0) + 1

    return frequency

def main():
    file_path = 'c:\\Users\\USER\\Desktop\\abc.txt'
    
    with open(file_path, 'r', encoding='utf-8') as file:
        text = file.read()

    frequencies = count_word_frequency(text)
    sorted_frequencies = sorted(frequencies.items(), key=lambda x: x[1], reverse=True)[:3]
    
    print("\n단어 빈도수:")
    for word, freq in sorted_frequencies:
        print(f"{word}: {freq}")

if __name__ == "__main__":
    main()

 

주석 있는 코드

# 단어 빈도수를 세는 함수를 정의합니다.
def count_word_frequency(text):
    # 주어진 텍스트를 단어별로 분할합니다.
    words = text.split()
    # 빈도수를 저장할 빈 딕셔너리를 생성합니다.
    frequency = {}

    # 분할된 단어들을 순회하면서 빈도수를 세어 딕셔너리에 저장합니다.
    for word in words:
        # 단어를 소문자로 변환하고, 구두점을 제거합니다.
        word = word.lower().strip(",.!?")  
        # 딕셔너리에 단어의 빈도수를 갱신하거나 추가합니다.
        frequency[word] = frequency.get(word, 0) + 1

    # 완성된 빈도수 딕셔너리를 반환합니다.
    return frequency

# 메인 함수를 정의합니다.
def main():
    # 읽을 파일의 경로를 지정합니다.
    # 본인 파일 경로를 사용하셔야합니다!
    file_path = 'c:\\Users\\USER\\Desktop\\파일이름.txt'
    
    # 지정된 파일을 읽기 모드로 열고, 내용을 읽어옵니다.
    with open(file_path, 'r', encoding='utf-8') as file:
        text = file.read()

    # 읽어온 텍스트에 대해 단어 빈도수를 계산합니다.
    frequencies = count_word_frequency(text)

    # 계산된 빈도수를 내림차순으로 정렬하고 상위 10개를 선택합니다.
    sorted_frequencies = sorted(frequencies.items(), key=lambda x: x[1], reverse=True)[:10]
    
    # 단어 빈도수를 출력합니다.
    print("\n단어 빈도수:")
    for word, freq in sorted_frequencies:
        print(f"{word}: {freq}")

# 파이썬 스크립트가 직접 실행될 때만 메인 함수를 실행합니다.
if __name__ == "__main__":
    main()

 


TXT파일 만들기

예시 글은 Lorem Ipsum에서 가져왔습니다.

https://www.lipsum.com/

 

Lorem Ipsum - All the facts - Lipsum generator

What is Lorem Ipsum? Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type spec

www.lipsum.com

 

파일을 생성할 때 '.txt'를 붙이지 않고 생성해야 코드실행에 문제가 없습니다!

* 아닐수도..

 


출력 결과

728x90