import nltk
# nltk.download('wordnet') # 유의어 사전 다운받기
from nltk.corpus import wordnet # 말뭉치 내 유의어 사전
# nltk.download('punkt')
from nltk.tokenize import word_tokenize, sent_tokenize # 단어별, 문장별로 잘라주는 패키지
# nltk.download('averaged_perceptron_tagger') # 품사 사전
from wordcloud import WordCloud # 워드 클라우드 패키지
import matplotlib.pyplot as plt
from PIL import Image # 이미지 인식 패키지
import numpy as np
from wordcloud import STOPWORDS # 의미 없는 글자가 정의되어 있는 내용
# nltk.download('stopwords')
from nltk.corpus import stopwords # nltk 내 stopword
from collections import Counter # 갯수 세기

# 자연어처리(NLP) : 사람이 쓰는 말을 컴퓨터에게 이해시키기
# 방법 1) 시소러스 활용, 2) 통계 기반, 3) 추론
# 시소러스 활용 - 시소러스 : 유의어사전
# - 단점: 변화하는 단어 뜻에 맞춰 수동으로 수정해야함 -> 노동이 많이 들어감

# 단어의 유사성
# print(wordnet.synsets('car')) # synsets('단어') : 단어 뜻 제목의 그룹
c1 = wordnet.synset('car.n.01') # synset('단어') : 단어 뜻 하나의 제목
# print(c1.definition()) # definition() : 정의
# print(c1.lemma_names()) # lemma_names(): 동의어 그룹의 단어
# print(c1.hypernyms()) # hypernyms() : 상위어
# print(c1.hypernym_paths()) # hypernyms_paths(): 상위어 경로

e = wordnet.synset('entity.n.01')
# print(e.definition())

# 단어와 단어 사이의 유사도
# print(wordnet.synsets('rabbit'))
# print(wordnet.synsets('book'))
r1 = wordnet.synsets('rabbit.n.01')
b1 = wordnet.synsets('book.n.01')
d1=wordnet.synset('dog.n.01')
# print(c1.path_similarity(r1))
# path_similarity(비교단어): 비교단어와 기준 단어의 유사도<-경로 찾기.
# 유사도 범위: 0 ~ 1
# print(c1.path_similarity(b1))
# print(r1.path_similarity(d1))

# 문장 분할
text = "Hello World. It's good to see you. Thanks for buying this book."

w = word_tokenize(text) # 특수문자도 따로 자름
s = sent_tokenize(text) # 마침표 기준으로 자름
# print(w) # type: list
# print(s)

# 대소문자 변형
# print('Happy'.upper())
# print('Happy'.lower())
# for word in w:
# print(word.lower())
w = [word.lower() for word in w]
# print(w)

# 단어의 단복수 처리
l = nltk.WordNetLemmatizer() # WordNetLemmatizer(): 단어의 복수형을 단수형과 같은 단어로 처리
# print(l.lemmatize('books'))
# print(l.lemmatize('boys'))

# 품사 처리
# print(nltk.pos_tag(['girl', 'beautiful', 'buy']))

# 워드 클라우드
# terminal : pip install 'wordcloud-1.7.0-cp36-cp36m-win_amd64'
# 파일 다운 : https://www.lfd.uci.edu/~gohlke/pythonlibs/
data = open('data\\alice.txt').read()
data = data.lower()
# print(data)
wc = WordCloud(background_color='white')
word = wc.generate(data)
# plt.imshow(word) # imshow(): 이미지 보기
# plt.axis('off') # axis('off'): 축삭제
# plt.show()

# 배경 마스크를 적용한 워드 클라우드
img = Image.open('img\\alicebg.png')
# print(img)
mask = np.array(img) # numpy 배열로 변경후 mask로 적용
# print(mask)
wc = WordCloud(mask=mask, background_color='white')
word = wc.generate(data)
# plt.imshow(word)
# plt.axis('off')
# plt.show()

# 단어 제외
# print(STOPWORDS)
sw = STOPWORDS
sw.add('said')
mask=np.array(img)
# print(mask)
data=open('data\\alice.txt').read()
mask=np.array(img)
wc=WordCloud(mask=mask, background_color='white',stopwords=sw)
# wc=WordCloud()
word=wc.generate(data)
# plt.imshow(word)
# plt.axis('off')
# plt.show()
# print(stopwords.words('english')) # stopwords.words('english'): 영어의 기본 단어 목록
# data = open('data\\alice.txt').read()
# words = word_tokenize(data)
# words = [w.lower() for w in words]
# print(words)

# 단어 정리후 워드 클라우드
# for w in words:
# if w not in stopwords.words('english') and w.isalnum(): # 단어 제외 & 특수문자 제거
# isalnum(): 숫자거나 문자인가
# print(w)
# 불필요한 단어 제외
# word = [w for w in words if w not in stopwords.words('english') and w.isalnum()]
# 단어 단복수형 통일
# l = nltk.WordNetLemmatizer()
# word = [l.lemmatize(w) for w in word]
# print(word)
# 정리한 단어 파일 저장
# with open('data\\alice2.txt', 'w') as f:
# f.write(' '.join(word)) # '구분자'.join(리스트): 구분자를 기준으로 단어 분리 후 리스트 단어 합치기
data = open('data\\alice2.txt').read()
# 리스트로 만들기
wordlist = data.split(' ') # 데이터.split('구분자'): 구분자를 없애고 단어를 분할해 리스트로 만들기
# 제외 단어 설정
stops=['alice', 'said']
wordlist = [w for w in wordlist if w not in stops]
# 단어당 사용된 회수 구하기
cnt = Counter(wordlist) # Counter(리스트): 리스트 내 단어 세기
print(cnt)
print(type(cnt)) # Counter 객체
cnt = dict(cnt) # dictionary형으로 변경
# 워드 클라우드 그리기
wc = WordCloud(mask=mask, background_color='white', max_words=30).generate_from_frequencies(cnt)
# generate_from_frequencies(): 딕셔너리 데이터의 단어 처리
# max_words: 클라우드에 나올 최대단어 설정
plt.imshow(wc)
plt.axis('off')
plt.show()

cyr님의 창작활동을 응원하고 싶으세요?