ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 스파르타 힙한 취미 코딩 - 파이썬 혼자놀기 패키지 3일차 개발일지
    개발일지 2021. 9. 24. 01:22

    [Week I Learned]

     

    *Notion

    https://www.notion.so/3-fb4101adb94b4bb1acbd08f5554fd692

     

    [스파르타코딩클럽] 파이썬 혼자놀기 패키지 - 3일차

    강의자료 시작에 PDF파일을 올려두었어요!

    www.notion.so

     

     

     

    *텍스트 파일 쓰기

     

    f = open("test.txt", "w", encoding="utf-8")
    f.write("안녕, 스파르타!")
    f.close()

     

     

    =>txt파일 생성

     

     

     

     

    f = open("test.txt", "w", encoding="utf-8")
    f.write("안녕, 스파르타!\n")
    f.write("안녕, 스파르타!\n")
    f.write("안녕, 스파르타!\n")
    f.close()

     

     

    =>\n: 줄바꿈

     

     

     

     

    f = open("test.txt", "w", encoding="utf-8")
    f.write("안녕, 스파르타!\n")

    for i in [1,2,3,4,5]:
    f.write(f"{i}번째 줄이에요\n")

    f.close()

     

     

     

     

     

    *텍스트 파일 읽기

     

    with open("test.txt", "r", encoding="utf-8") as f:
        lines = f.readlines()
        for line in lines:
            print(line)

     

     

     

     

    text = ''
    with open("test.txt", "r", encoding="utf-8") as f:
         lines = f.readlines()
         for line in lines:
              text += line

    print(text)

     

     

     

     

    [워드 클라우드]

     

    1. 카카오톡 대화 내보내기, 해당 파이썬 파일 있는 폴더에 저장

    2. 패키지 파일 'wordcloud' 설치

    3. 한글 폰트 설정

      import matplotlib.font_manager as fm

      # 이용 가능한 폰트 중 '고딕'만 선별
      for font in fm.fontManager.ttflist:
          if 'Gothic' in font.name:
              print(font.name, font.fname)

     

    =>원하는 폰트 로케이션 복사 (ex: C:\Windows\Fonts\COPRGTB.TTF)

     

     

    4. 워드 클라우드 만들기

    from wordcloud import WordCloud

    wc = WordCloud(font_path='font_path', background_color="white", width=600, height=400)
    wc.generate(text)
    wc.to_file("result.png")

     

     

    font_path 부분에 폰트 로케이션 붙여넣기 (윈도우의 경우 역슬래시\를 슬래시/로 바꾸기)

     

     

    from wordcloud import WordCloud

    text = ''
    with open("bookclub.txt", "r", encoding="utf-8") as f:
         lines = f.readlines()
         for line in lines:
              text += line

    wc = WordCloud(font_path='C:/Windows/Fonts/NanumBarunGothicBold.ttf', background_color="white", width=600, height=400)
    wc.generate(text)
    wc.to_file("result.png")

     

    =>이름, 시간 등이 너무 많으니 데이터 클렌징을 통해 대화내용만 뽑아낼 것

     

     

     

     

    [데이터 클렌징]

     

    - 전처리 과정

     

     

    *앞줄 자르기

     

    text = ''
    with open("bookclub.txt", "r", encoding="utf-8") as f:
         lines = f.readlines()
         for line in lines[5:]:   =>5번째 줄부터 표시해줘
               text += line

    print(text)

     

     

     

    *시스템 메시지 거르기

    사람들이 말하는 부분은 ] [ 가 공통으로 들어감

    따라서, ] [ 가 있는 줄만 읽어달라고 하면 됨

     

    text = ''
    with open("bookclub.txt", "r", encoding="utf-8"as f:
         lines = f.readlines()
         for line in lines[5:]:   

             if '] [' in line:
               text += line

    print(text)

     

     

     

    *대화 메시지만 거르기

    ] 로 split해서 2번째만 읽어줘

     

    text = ''
    with open("bookclub.txt", "r", encoding="utf-8"as f:
         lines = f.readlines()
         for line in lines[5:]

             if '] [' in line:
               text += line.split('] ')[2]

     

     

     

    *이모티콘, 사진, 그림, ㅋㅋㅋ 등등 불필요한 데이터 거르기

     

    text = ''
    with open("bookclub.txt", "r", encoding="utf-8"as f:
         lines = f.readlines()
         for line in lines[5:]:

             if '] [' in line:
               text += line.split('] ')[2].replace('ㅎ','').replace('이모티콘\n','').replace('사진\n','').replace('삭제된 메시지입니다','').replace('https','')

     

    '이모티콘 예쁘네요' 라고 할때의 이모티콘과 실제 '이모티콘'은 다름.

    실제 이모티콘이나 사진은 한 줄 띄워지는 성질이 있어서 이모티콘\n, 사진\n 로 해주면 텍스트 이모티콘, 사진은 지워지지 않음

     

     

     

    *원하는 모양으로 만들기

    경계선이 뚜렷한 사진을 다운 받아서 폴더에 넣음

     

    - 마스킹 된 워드 클라우드 만들기

    from PIL import Image
    import numpy as np

    mask = np.array(Image.open('cloud.png'))
    wc = WordCloud(font_path='font_path', background_color="white", mask=mask)
    wc.generate(text)
    wc.to_file("result_masked.png")

     

     

    최하단에 붙여넣고 임포트 부분만 최상단으로 올려주기

     

    *Problem

     1. 더 클렌징 하고 싶은 데이터가 많은데 .replace를 일정 갯수 이상 붙이니 오류가 뜸

    SyntaxError: Non-UTF-8 code starting with '\xea' in file C:/Users/user/Desktop/sparta/projects/hipcoding/wrprac.py on line 11, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details

     

    *Try

     1. regex 설치, import re, 정규식 사용

Designed by Tistory.