데이터 분석 실습/Python

뉴스 3줄 요약하기

HanJW96 2023. 4. 20. 10:47

원본기사 : 카운트다운 들어간 아르테미스 계획…'달의 여신'은 미소지을까 (naver.com)

 

카운트다운 들어간 아르테미스 계획…'달의 여신'은 미소지을까

29일(현지시간) 발사 예정인 ‘우주발사시스템’(SLS)로켓이 미국 플로리다주 케네디 우주센터의 발사대 39B에 설치돼 있다. (사진=나사) 2025년 인류를 달로 보내기 위한 첫 번째 여정이 하루 앞으

n.news.naver.com

바이너리 파일 읽기

# 기사 이미지


f = open("news/image", 'rb')
image = f.readlines()
f.close()

print(image) 

# 기사 본문


f = open("news/article", 'rb')
article = f.readlines()
f.close()

print(article) 

# 아직 코드화 되어있는 상태라 알아 볼 수 없다.

base64 디코딩

# 기사 이미지 디코딩


import base64
file_base64 = image[0]

 

path = "news/image.jpg"
with open(path, 'wb') as f:
    decoded_data = base64.decodebytes(file_base64)
    f.write(decoded_data)

 

#base64를 불러와서 이미지 디코딩 path는 파일경로

 

# 이미지 확인


from PIL import Image
img = Image.open(path)
img

 

#PIL패키지를 이용해 이미지 확인 

#설치는 pip install pillow

# 기사 본문 디코딩


file_base64 = article[0]
decoded_data = base64.decodebytes(file_base64)

 

decoded_data

#바이트 형식의 문자열로 먼저 디코딩

#utf 또는 ascii형식으로 한번 더 디코딩 필요

 

article = decoded_data.decode('utf-8')

print(article)

문서 요약/키워드 추출

#gensim라이브러리를 이용하기

#gensim 최신 버전은 요약이 지원이 안되므로 3.7.3버전으로 설치해야함

#pip install gensim==3.7.3

 

from gensim.summarization.summarizer import summarize
from gensim.summarization.textcleaner import split_sentences

 

# 단어수 기반 요약 (word_count)


print(summarize(article, word_count=50))

 

#50글자 요약


print(summarize(article, ratio=0.1))

 

# 비율 기반 요약 (ratio)   ratio=0.1 -> 전체의 10%로 요약하기

 

article_summarized = summarize(article, ratio=0.1)

 

#요약한 기사를 새로운 변수에 삽입 

 

키워드 추출

 

import collections
import textwrap
import re

 

# 줄바꿈 정렬


article_align = textwrap.fill(article, width=50)
print(article_align)

 

#기사를 보기좋게 정렬

#50글자 마다 줄바꿈

# 단어 추출

words = re.findall(r'\w+', article_align)
print(words)

# 빈도수 산출

counter = collections.Counter(words)
print(counter)

# 키워드 추출

print(counter.most_common(5))

#가장 많이 나온 5개 단어 

keywords = counter.most_common(5)[1:]
 
#'있다' 는 빼고 4개의 단어 keywords 변수에 삽입

요약 리포트 작성

from IPython.display import Image
Image(filename=path, width=300)
 
#이미지 불러오기
 
print(article_summarized)
 
#요약문 불러오기
 
keys = ['# ' + elem[0for elem in keywords]
keys = ' '.join(keys)
print(keys)
 
#키워드를 따옴표를 제거하고 #을 추가해서 해시태그 느낌으로 출력
 

 

html 파일 저장

htmlfile = open("/content/drive/news/summary.html""w")
htmlfile.write("<html>\n")
htmlfile.write ("<h1>"'카운트다운 들어간 아르테미스 계획…"달의 여신"은 미소지을까' + "</h2>\n"
htmlfile.write ("<img src='image.jpg'/>\n")
htmlfile.write ("<h2>"+ article_summarized + "</h2>\n"
htmlfile.write ("<h2 style='background-color:powderblue;''>"+ keys + "</h2>\n"
htmlfile.write("</html>\n")
htmlfile.close()