Python

파이썬: 파일명을 입력하면 워드클라우드(Word Cloud) 이미지 생성

coding-abc.tistory.com 2025. 8. 17. 07:56
반응형

워드클라우드(Word Cloud)란 텍스트 데이터에서 단어의 빈도나 중요도를 시각적으로 표현하는 기법입니다.

👉 쉽게 말해, 긴 글에서 **“어떤 단어가 자주 나오나?”**를 그림처럼 보여주는 도구를 말합니다.

 

📌 특징

  • 단어 크기: 많이 등장하는 단어일수록 크게 표시됨
  • 배치: 보통 구름 모양처럼 흩뿌려진 형태로 배치
  • 색상: 단어의 그룹, 빈도, 또는 무작위 색상으로 꾸밀 수 있음
  • 목적: 텍스트 데이터를 한눈에 요약해서, 어떤 단어가 핵심적인지 쉽게 파악 가능

 

📖 예시

  • 뉴스 기사에서 자주 등장하는 키워드를 분석
  • 고객 리뷰에서 많이 언급되는 단어 시각화
  • 설문조사에서 응답자들이 자주 사용한 단어 확인

 

📊 활용 분야

  • 데이터 분석 및 텍스트 마이닝
  • 여론 분석 (SNS, 댓글, 리뷰)
  • 교육 및 발표 자료 시각화

 


 

아래 코드는 파일명을 입력하면 워드클라우드(wordcloud)를 생성해 주는 파이썬 소스입니다.

아래의 코드를 실행하기 위해서는 2개의 라이브러리가 설치되어야 합니다.

pip install wordcloud
pip install matplotlib

 

파이썬 소스

# wordcloud_from_file.py
import re
import sys
from pathlib import Path

import matplotlib.pyplot as plt
from wordcloud import WordCloud

# ===== 사용자 환경에 맞게 한글 폰트 경로 설정 =====
# 예: Windows
FONT_PATH = r"C:\Windows\Fonts\malgun.ttf"
# macOS: FONT_PATH = "/System/Library/Fonts/AppleSDGothicNeo.ttc"
# Linux: FONT_PATH = "/usr/share/fonts/truetype/nanum/NanumGothic.ttf"

# 기본 불용어(원하는 단어 추가/삭제)
KOREAN_STOPWORDS = {
    "그리고", "그러나", "하지만", "또한", "것", "등", "수", "및",
    "대한", "하는", "했다", "하기", "에서", "으로", "에게", "보다",
    "중", "등의", "하여", "하면", "했다가", "하면", "처럼", "같은",
}
EN_STOPWORDS = {
    "the", "a", "an", "and", "or", "of", "to", "in", "on", "for", "is", "are",
    "was", "were", "it", "that", "this", "with", "as", "by", "from",
}

def load_text(path: Path) -> str:
    # 다양한 인코딩 시도
    for enc in ("utf-8", "cp949", "euc-kr"):
        try:
            return path.read_text(encoding=enc)
        except Exception:
            continue
    # 그래도 실패하면 에러
    raise UnicodeDecodeError("unknown", b"", 0, 1, "텍스트 인코딩을 감지하지 못했습니다.")

def tokenize(text: str):
    """
    한글/영문 단어만 추출.
    - 한글: 2자 이상만 사용 (조사/형태 축약 방지)
    - 영문: 2자 이상
    """
    # 한글 음절 범위 가정, 영문 단어 포함
    tokens = re.findall(r"[가-힣]{2,}|[A-Za-z]{2,}", text)
    return [t.lower() for t in tokens]

def main():
    try:
        filename = input("워드클라우드를 만들 텍스트 파일 경로를 입력하세요: ").strip().strip('"').strip("'")
        path = Path(filename)
        if not path.is_file():
            print(f"[오류] 파일을 찾을 수 없습니다: {path}")
            sys.exit(1)

        text = load_text(path)
        tokens = tokenize(text)

        # 불용어 적용
        stopwords = set()
        stopwords |= {w.lower() for w in KOREAN_STOPWORDS}
        stopwords |= {w.lower() for w in EN_STOPWORDS}

        filtered = [t for t in tokens if t not in stopwords]

        if not filtered:
            print("[경고] 유효한 단어가 없습니다. 불용어를 줄이거나 텍스트를 확인하세요.")
            sys.exit(1)

        # 워드클라우드 생성
        wc = WordCloud(
            width=1600,
            height=900,
            background_color="white",
            font_path=FONT_PATH,   # 한글 폰트가 없으면 한글이 깨집니다.
            collocations=False,    # '뉴+욕' 같은 중복 bigram 방지
            max_words=500
        ).generate(" ".join(filtered))

        # 파일명 기반 출력 경로
        out_png = path.with_suffix("")  # 확장자 제거
        #out_png = out_png.parent / f"{out_png.name}_wordcloud.png"
        out_png = "c:/temp/" + f"{out_png.name}_wordcloud.png"
        
        # 저장 + 표시
        wc.to_file(str(out_png))
        print(f"[완료] 워드클라우드 이미지를 저장했습니다: {out_png}")

        plt.figure(figsize=(12, 7))
        plt.imshow(wc, interpolation="bilinear")
        plt.axis("off")
        plt.tight_layout()
        plt.show()

    except Exception as e:
        print(f"[에러] {e}")
        sys.exit(1)

if __name__ == "__main__":
    main()

 

파일명 입력 예:

c:/temp/news.txt

 

위와 같이 파일명을 입력하면 확장명을 제외한 "news_wordcloud.png" 파일을 생성해 줍니다.

c:\temp 폴더에 생성됩니다 - 이 폴더를 확인해 보세요.

 

텍스트 파일 예:

news.txt
0.01MB

 

생성된 워드클라우드 이미지

파이썬, 워드클라우드

반응형