🖥️ IT, 컴퓨터/🐍 Python

[Python] 파이썬으로 카톡 채팅방 단어 분석하기

김 홍시 2025. 6. 20.
반응형

준비물

 

- KoNLPy 설치 (아래 글 참고! 잘 정리해주심)

https://codevang.tistory.com/351

 

파이썬 한글 형태소 분석, 태깅 라이브러리 KoNLPy 설치하기

KoNLPy 한국어 텍스트를 분석할 수 있는 kkma(꼬꼬마), Okt 등의 라이브러리를 모아둔 패키지입니다. 업데이트된지 오래되긴 했지만 아무래도 ""nltk"와 같이 외국어 위주의 라이브러리보다는 활용성

codevang.tistory.com

 

 

- 카톡 채팅 전체 txt 파일

 

 

 

 

 

 

 

이런 KakaoTalkChats.txt 라는 파일이 생김

 

 

카톡 채팅방 자주 쓴 단어 분석하는 파이썬 코드

pip install konlpy matplotlib

 

먼저 konlpy와 matplotlib 를 설치

 

import re

chat_lines = []

for line in lines:
    line = line.strip()
    if not line:
        continue

    # 날짜만 있는 줄은 건너뜀
    if re.fullmatch(r"\d{4}년 \d{1,2}월 \d{1,2}일 [오전|오후]+ \d{1,2}:\d{2}", line):
        continue

    # 메시지 줄 (예: 2024년 5월 31일 오전 12:54, ㅇ : 정산을 시작합니다!)
    match = re.match(r"^\d{4}년 \d{1,2}월 \d{1,2}일 (오전|오후) \d{1,2}:\d{2}, (.+?) : (.+)", line)
    if match:
        msg = match.group(3).strip()
        chat_lines.append(msg)
        
print(f"총 메시지 줄 수: {len(chat_lines)}")
for msg in chat_lines[:10]:
    print(msg)

 

 

 

 

먼저 채팅 문장들이 제대로 인식되는지 확인.

필자 사례는 총 메시지 줄 수 (chat_lines의 len)이 74,761개였음

 

그리고 첫 대화의 일부를 출력해보니 잘 인식된 것을 확인했음

 

 

 

다음으로 아래 코드 입력하면 끝 

from konlpy.tag import Okt
from collections import Counter
import matplotlib.pyplot as plt

# 4. 전체 텍스트 결합
text = ' '.join(chat_lines)

# 5. 형태소 분석 및 명사 추출
okt = Okt()
nouns = okt.nouns(text)

# 6. 불용어 정의
#stopwords = ['이', '그', '저', '거', '좀', '진짜', '근데', '안', '같이', '나', '너', '우리', '뭐', 'ㅋㅋ', 'ㅎㅎ', 'ㄱㄱ', '되', '게', '아니']

# 7. 불용어 제거 + 한 글자 단어 제거
filtered = [word for word in nouns if word not in stopwords and len(word) > 1]

# 8. 단어 빈도 계산
word_counts = Counter(filtered)
top_words = word_counts.most_common(20)

# 9. 결과 출력
print("📊 가장 많이 사용된 단어 TOP 20:")
for word, count in top_words:
    print(f"{word}: {count}회")

 

위의 불용어는 직접 수정하기

 

 

 

 

 

반응형

댓글