Python의 WordCloud에서 놀아 본 [제재 : 吾輩는 고양이이다]

10704 단어 wordcloudPython3mecab

계기



이벤트에 참가했을 때의 옆의 좌석 쪽이 사용하고 있었던 것을 보고 장래적으로 도움이 될 기술을 배울 수 있을 것이라고 생각해, 방법을 조사하면서 WordCloud 를 사용해 보았다. 문서는 →여기

WordCloud란?



문장 중에서 출현 빈도가 높은 단어를 선택하고, 그 빈도에 따른 크기로 도시하는 수법이다. 참조

했던 일



이번은 액배는 고양이인 소설을 바탕으로 WordCloud를 사용하여 간단한 이미지를 작성했다. (이하 참조)

 

※이미지


소설에 대해서는 푸른 하늘 문고의 것(전처리 실시)을 사용했다. 이하, 코드와 비망록이다.

 
  • 라이브러리 설치 및 마스크 이미지 (고양이 이미지) 준비
  • 
    from wordcloud import WordCloud
    import MeCab
    import re
    from PIL import Image
    import numpy as np
    
    mask = np.array(Image.open('イメージ画像のパスを入力'))
    mask = np.where(mask == 0, 255, 0)
    

     
  • 형태소 분석에서 단어 추출을 수행하고 소설 데이터를 성형
  • 
    with open("./前処理済/wagahaiwa_nekodearu.txt", mode='r', encoding='utf-8') as f:
        text_list = [i.strip() for i in f]
    text = "".join(text_list)
    
    stop_words = ['する', 'せる', 'られる', 'あの', 'する', 'ある', 'とこ', 'なる', 'ない', 'ああ', 'れる', 'さん', 'やる', 'この', 'どう', 'そう']
    font_path = "/Library/Fonts/BIZ-UDGothicR.ttc"
    
    mecab = MeCab.Tagger("-Ochasen")
    mecab_str =  mecab.parse(text)
    mecab_list = mecab_str.replace('\t', 't').split('\n')
    lang_meta_list = [re.split('[t-]' ,lang_meta_str) for lang_meta_str in mecab_list]
    
    for lang_meta in lang_meta_list : 
        if "助詞" in lang_meta :
            continue
        if "助動詞" in lang_meta :
            continue
        if "非自立" in lang_meta :
            continue  
        if "サ変・スル" in lang_meta :
            continue
        if "サ変接続" in lang_meta :
            continue
        #if "一般" in lang_meta :
            #continue
        if "数" in lang_meta :
            continue
        if "記号" in lang_meta :
            continue    
        else :
            try:
                lang = lang_meta[2]
                print(lang_meta)
                text_list.append("{}\t".format(lang))
            except:
                pass
    
    text = ("").join(text_list)
    

     
  • WordCloud 구현
  • 
    wordcloud = WordCloud(font_path=font_path, font_step=1, mask=mask, background_color="white", contour_width=1, repeat=1, contour_color='purple', colormap='Praples', stopwords=set(stop_words)).generate(text)
    wordcloud.to_file("./吾輩は猫である.png")    
    

     

    고배는 고양이입니다. png를 열면 방금 전
     

    ※이미지


    출력됨

     

    완료

    요약


  • 적은 코드로 작성 가능.
  • 보기 좋게 재미있어 선물로 사용할 수 있다. (※ 개인적 의견)
  • wordcloud의 매개 변수를 조금 더 원합니다. (다른 wordcloud 포함 등 ...)
  • Mecab의 라이브러리를 즐겁게 배울 수 있는 계기가 된다.
  • 문서가 많이 존재하기 때문에 다루기 쉽다.

  •  
    이번에는 소설의 문서를 사용해 고양이의 이미지를 마스크 이미지로 wordcloud를 실시했지만, 동화의 스토리를 사용해 그 동화에 나오는 캐릭터를 마스크 이미지로서 출현 빈도가 높은 단어로 가득 채우는 것도 흥미롭다고 생각했다.
     
     

    이상

    좋은 웹페이지 즐겨찾기