크롤링해온 뉴스를 바탕으로 각 카테고리별로 word_cloud를 생성했다. 뉴스에서 가장 많이 언급된 이슈가 무엇인지 한눈에 파악할 수 있다.
일반적으로 많이 사용되는 단어들을 불용어 list에서 빠지도록 처리했다.
from konlpy.tag import Okt
from collections import Counter
from wordcloud import WordCloud
import matplotlib.pyplot as plt
import json
# 형태소 분석기 초기화
okt = Okt()
# 불용어 목록
stopwords = set(['스마트', '건설', '건설업', '사고', '사망', '처벌', '기술', '조선업', '조선', '선박', '이슈', '기업', '산업', '재해', '중대', '안전', '기자', '연합뉴스', '에서', '이다', '것이다', '있다', '등', '이', '그', '저', '시장', '동향'])
def extract_titles_by_category(json_data, category_id):
text = ''
for article in json_data:
if 'Title' in article and article['Title'] and article['CategoryID'] == category_id:
text += article['Title'] + ' '
return text
def generate_wordcloud(text, category_id):
# 명사 추출 및 불용어 제거
nouns = [noun for noun in okt.nouns(text) if noun not in stopwords and len(noun) > 1]
word_counts = Counter(nouns)
# 워드 클라우드 생성
wordcloud = WordCloud(
font_path='malgun.ttf', # 한글 폰트 경로
width=800,
height=400,
background_color='white'
).generate_from_frequencies(word_counts)
return wordcloud
# JSON 파일 경로 지정
json_file_path = 'musma_news_data.json'
# JSON 파일에서 데이터 읽어오기
with open(json_file_path, 'r', encoding='utf-8') as json_file:
data = json.load(json_file)
# 각 카테고리별로 워드 클라우드 생성 및 파일로 저장
for category_id in range(4):
text = extract_titles_by_category(data, category_id)
wordcloud = generate_wordcloud(text, category_id)
# 파일명 지정
image_file_name = f'wordcloud_{category_id}.png'
# 워드 클라우드 이미지를 파일로 저장
wordcloud.to_file(image_file_name)
print(f'Word Cloud saved as {image_file_name}')
결과
스마트 조선 ESG 경영/스마트 건설 ESG 경영
IT 동향/산업재해, 중대재해
728x90
'학교생활 (프로젝트&강의정리) > 소프트웨어공학&비즈니스애널리틱스 (최성철 교수님) 2023-2' 카테고리의 다른 글
word_cloud flask API 성공 (2) | 2023.12.12 |
---|---|
ANIOP 부산 지산학 네트워킹 데이 발표 (0) | 2023.12.11 |
클리핑된 뉴스 모델에 통과시켜서 성능확인하기 (0) | 2023.12.10 |
뉴스 클리핑 코드 구현 (4) | 2023.12.09 |
AWS S3 커스텀 모델에 json 뉴스 결과 저장 성공!! (6) | 2023.11.22 |