[Python] WordCloud 이미지 생성 코드

강우용·2024년 7월 17일

Python 워드클라우드 소스코드 기록

import time
from PIL import Image
# from konlpy.tag import Okt

from pprint import pprint
import numpy as np
import urllib.parse
import xml.sax.saxutils as saxutils

import os
import sys

from wordcloud import WordCloud, STOPWORDS
import matplotlib.pyplot as plt
from eunjeon import Mecab
# import Mecab
from collections import Counter



# import nltk

# okt = Okt()

# # # 하나의 문장을 토큰화 한 후 텍스트와 품사태깅을 / 구분자로 묶어준다.
# def tokenizing(docs):
    # return ['/'.join(t) for t in okt.pos(docs,norm=True, stem=True)]

# import nltk

# term_frequency()함수는 위에서 만든 selected_words의 갯수에 따라서 각 리뷰와 매칭하여 상위 텍스트가 
# 각 리뷰에 얼만큼 표현되는지 빈도를 만들기 위한 함수
# def term_frequency(doc):
    # return [doc.count(word) for word in selected_words]



## 워드클라우드 컬러 커스터마이징
# def make_colors(word,font_size,position,orientation,random_state,**kwargs):
	# color = "#d4b4f8"
	# return color


f = open("./20240115_댓글.txt", 'r')
# f = open("./0530_WD.txt", 'r', encoding='utf-8')

stringdata = f.read()
# stringdata = "안녕 반가워 고마워 최고야 훌륭해 멋져"

print(stringdata)

# stringdata = sys.argv[1]

	
def draw_wordcloud(text):

	## 특정 단어 없애기
	
	text = text.replace('\n','')
	text = text.replace('\t','')

	##### 한국어사전 기준의 명사들만 리스트로 만들기 #####
	engine = Mecab()
	nouns = engine.nouns(text)
	nouns = [n for n in nouns if len(n) > 1]

	#### 전달받은 문자열을 띄어쓰기 기준으로 명사 리스트 생성 ####
	# nouns = text.split()
	# nouns = text

	print("----print(nouns)----")
	print(nouns)
		
    #### 빈도수를 계산 #####
	count = Counter(nouns)
		
	######## 몇개의 단어 추출할 건지 설정 ##########
	tags = count.most_common(100)
	######## 몇개의 단어 추출할 건지 설정 ##########
	
	print("----print(count.most_common(100)) 단어별 빈도수 리스트 생성----")
	print(tags)
	
	#WordCloud, matplotlib: 단어 구름 그리기
	font_path = 'KBFGTextM.ttf'
	wc = WordCloud(font_path=font_path,background_color='white',width=800, height=600)
	
	# wc = WordCloud(min_font_size=35,max_font_size=50,font_path=font_path,background_color='white', width=800, height=600)
	
	# 빈도수로 워드클라우드 생성
	cloud = wc.generate_from_frequencies(dict(tags))
	# cloud = wc.generate(tags)

	## color customizing
	# cloud = cloud.recolor(color_func=make_colors,random_state=True)
	
	# cloud = wc.generate(text)
	plt.figure(figsize=(10,8))
	plt.axis('off')
	plt.imshow(cloud, interpolation='lanczos')
	#plt.savefig('wordcloud.png')
	
	######### 생성될 이미지 파일명 #########
	plt.savefig("./240116_6.png")
	######### 생성될 이미지 파일명 #########
	
	plt.close('all')
	
# cloud_mask = np.array(Image.open("cloudmask2.png"))

draw_wordcloud(stringdata)

profile
I believe that if you spend 30 minutes every day taking a small step towards your dream, you will reach the dream someday.

0개의 댓글