[Python] 텍스트파일

정현석·2020년 10월 6일

스파르트 코딩클럽


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

#텍스트 파일 읽기
with open("test.txt", "r", encoding="utf-8") as f:
    lines = f.readlines()
    for line in lines:
        print(line)
        
#폰트 검색
import matplotlib.font_manager as fm

# 이용 가능한 폰트 중 '고딕'만 선별
for font in fm.fontManager.ttflist:
    if 'Gothic' in font.name:
        print(font.name, font.fname)
        
#워드 클라우드
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")
        
# 데이터 클렌징
for line in lines:
    if '] [' in line:
        text += line.split('] ')[2].replace('ㅋ','').replace('ㅠ','').replace('ㅜ','').replace('사진\n','').replace('이모티콘\n','').replace('삭제된 메시지입니다','')


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

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")


profile
기록하는 벨로그

0개의 댓글