barcode

워드클라우드 코드에 기능 추가

Coding/Python

일단 Entrez랑 Text랑 추가된 기능이 조금 다름. 기본 맥락은 같습니다. 


공통 기능

워드클라우드용 마스킹 이미지를 불러오기 위한 파일 창 추가

 

from argparse import FileType
import tkinter
from tkinter import filedialog

추가 소환한 모듈(...)

 

root = tkinter.Tk()
root.withdraw()
dir_path = filedialog.askopenfilename(parent=root,initialdir="/home/koreanraichu",title='Please select a directory',filetypes = (("*.png","*png"),("*.jpg","*jpg"),("*.gif","*gif")))
image = np.array(Image.open(dir_path)) 
# 마스킹할 이미지(흰 바탕에 검정색을 권장함)
font_path = '/usr/share/fonts/나눔손글씨 바른히피.ttf'
wordcloud = WordCloud(font_path = font_path,stopwords=STOPWORDS,
                      background_color="#ffffff",colormap="magma",width = 800, height=800,
                      mask=image)
# Font path: 글꼴 설정하실 경우 여기에 쓰세요
# background color: wordcloud 배경 설정할 때 여기서 하세요 
# colormap: 워드클라우드 글자색을 여기서 바꿔주세요(matplotlib colormap 치면 많이 나옵니다)

글꼴은 고정된 상태이다. 

 

분기

공통적으로 워드클라우드를 저장하는 건 똑같은데, Text랑 Entrez랑 조금 다른 부분이 있다. 일단 텍스트부터 보고 가자. 

 

root = tkinter.Tk()
root.withdraw()
save_path = filedialog.asksaveasfilename(parent=root,initialdir="/home/koreanraichu",title='Please select a directory',filetypes = (("*.png","*png"),("*.jpg","*jpg"),("*.gif","*gif")))
image = np.array(Image.open(dir_path)) 
wordcloud = wordcloud.generate_from_text(text)
plot.figure(figsize=(15,15))
plot.axis('off')
plot.imshow(wordcloud)
plot.savefig(save_path)
plot.show()
print("wordcloud saved where {}".format(save_path))

이쪽이 Text에 적용된 코드. 파일명도 저기서 입력하면 된다. 

 

term = input("Entrez database에서 가져오고 싶은 주제가 뭔가요? (Title로 검색) \n")
year = input("특별히 보고 싶은 년도가 있나요? (optional, 없으면 공백으로 입력해주세요) \n")
if year: 
    terms = "{}[TITLE] AND {}[YEAR]".format(term,year)
else: 
    terms = "{}[TITLE]".format(term)

Entrez의 경우 일단 용어(그니까 논문 제목) 혹은 연도를 입력받되, 연도가 optional이다. 여기는 차후 저자 검색 등의 조건이 추가되면 elif 늘어나서 괴랄해 질 예정... 사실 핸들에 있는 걸 가져올 수 있으면 좋은데, 그게 사실상 불가능하다. 아마 나중에 검색어가 늘어나면 입력을 []까지 해서 받거나 코드단에서 수정하고 text처럼 될 지도 모름... 

 

if year:
    save_dir = "{}/{}&{}.png".format(save_path,term,year)
else: 
    save_dir = "{}/{}.png".format(save_path,term)

저장 경로가 뜨는 기본 골자는 같지만, 위에서 연도와 용어를 입력받기 때문에 파일명이 그걸로 자동 생성된다. 즉, 파일 이름을 입력하는 게 아니라 말 그대로 저장 경로만 선택해주면 된다. 


입력 관련 추가 수정사항

검색어 입력할 때 단어[조건] AND 단어[조건] 이런 식으로 통으로 입력해야 함. 대신 그걸로 파일명 만들어드립니다. 

예: Bacteria[TITLE] AND 2022[YEAR]

 

import re

일단 규식이형부터 불러봅니다

terms = terms.replace('[','-')
terms = terms.replace(']','-')
# 이스케이프 시퀀스 멕여도 안돼서 결국 이게 최선이었음... 
escape_terms = re.findall('-.{0,5}-',terms)
for i in escape_terms:
    terms = terms.replace(i,"")

일단 대괄호가 메타문자기때문에 저게 낑겨있으면 인식을 못해요 
근데 더 골때리는건 이스케이프 뭐시기 처리를 했는데도 불구하고 인식을 못해 
그래서 제한효소 DB때처럼 걍 대괄호를 다 하이픈으로 바꾸고 정규식으로 찾은 다음 빼버림 

그러니까 중간과정이 


Bacteria[TITLE] AND 2022[YEAR]
Bacteria-TITLE- AND 2022-YEAR-
Bacteria AND 2022

이렇게 되는거임. 

 

wordcloud saved where /home/koreanraichu/2022 AND bacteria.png.png

멘트 수정해야겠구만. 

+추가 기능: 그래프 여백 제거


일부 코드의 함수화

def replace_function (a):
    a = a.replace('[','-')
    a = a.replace(']','-')
    escape_terms = re.findall('-.{0,5}-',a)
    for i in escape_terms:
        a = a.replace(i,"")
    if '/' in a:
        a = a.replace('/','-')
    return a
# term 변환하는 거 함수로 뺐습니다. 근데 블록 실행하기 더 귀찮아진 건 기분탓인가... ㅡㅡ

엔트레즈: 입력받은 검색어 파일명으로 바꾸는 코드

 

def munjang_to_noun (a):
    a = ' '.join(a)
    a = okt.nouns(a)
    a = ' '.join(a)
    return a

한글: 텍스트 한글 처리하는 코드(저거 okt 돌리고 다시 join 안하면 작은따옴표 붙어서 나옴)

'Coding > Python' 카테고리의 다른 글

팩토리얼 로직 수정+계승 소수  (0) 2022.08.22
순열조합  (0) 2022.08.22
List comprehension  (0) 2022.08.22
완전수 찾는 코드  (0) 2022.08.22
Project restriction enzyme: 패치노트  (0) 2022.08.22