#!/usr/bin/env python # coding: utf-8 # # 파이썬 뉴스 텍스트 워드 클라우드 # # # # # ### 2017 http://financedata.kr # # 뉴스 워드 클라우드 # * feedparser, newspaper, konlpy 등 다양한 파이썬 라이브러를 활용 # * 뉴스 텍스트 데이터 수집, 전처리, 형태소 분석(명사추출), 출현 회수 카운트, 클라우드로 시각화까지 진행 # * (import를 제외하면) 약 20라인 정도의 코드 # In[1]: get_ipython().run_line_magic('matplotlib', 'inline') import feedparser import newspaper from konlpy.tag import Mecab from collections import Counter import matplotlib.pyplot as plt from wordcloud import WordCloud def draw_wordcloud_from_rss(rss_link): # feedparser, newspaper: RSS를 통해 뉴스의 본문을 수집 feeds = feedparser.parse(rss_link) links = [entry['link'] for entry in feeds['entries']] news_text ='' for link in links: article = newspaper.Article(link, language='ko') article.download() article.parse() news_text += article.text # konlpy, Mecab: 형태소 분석을 통해 본문에서 명사추출, 1글자는 단어는 삭제 engine = Mecab() nouns = engine.nouns(news_text) nouns = [n for n in nouns if len(n) > 1] # Counter: 단어수 세기, 가장 많이 등장한 단어(명사) 40개 count = Counter(nouns) tags = count.most_common(40) # WordCloud, matplotlib: 단어 구름 그리기 font_path = '/usr/share/fonts/truetype/nanum/NanumMyeongjoBold.ttf' wc = WordCloud(font_path=font_path, background_color='white', width=800, height=600) cloud = wc.generate_from_frequencies(dict(tags)) plt.figure(figsize=(10,8)) plt.axis('off') plt.imshow(cloud) # 경향신문 경제뉴스 RSS rss_link = 'http://www.khan.co.kr/rss/rssdata/economy.xml' draw_wordcloud_from_rss(rss_link) # # 1) feedparser: 뉴스 링크 수집 # * feedparser: RSS feed 파싱 라이브러리 # * 경향신문 경제뉴스 RSS를 통해 경제 뉴스 링크 수집(30개) # In[2]: import feedparser # 경향닷컴 경제뉴스 RSS feeds = feedparser.parse('http://www.khan.co.kr/rss/rssdata/economy.xml') links = [entry['link'] for entry in feeds['entries']] links # # 2) newspaper: 뉴스 본분 수집 # * newspaper: HTML문서에서 제목, 본문 등을 자동 식별하여 텍스트를 추출하는 라이브러리 # * 본문(article.text)를 모두 news_text에 누적하여 저장 # * 30개 뉴스의 본문 길이가 27213 자 # In[3]: import newspaper news_text ='' for link in links: article = newspaper.Article(link, language='ko') article.download() article.parse() news_text += article.text news_text[:1000] # In[4]: len(news_text) # # 3) KoNLpy + Mecab: 형태소 분석 # * 형태소 분석기로 명사만 추출 # * 1글자는 의미가 없다고 보고 삭제 # In[5]: from konlpy.tag import Mecab engine = Mecab() nouns = engine.nouns(news_text) # In[6]: len(nouns) # In[7]: nouns = [n for n in nouns if len(n) > 1] nouns[:20] # # 4) Counter: 단어 개수를 세기 # * 단어의 개수를 세고, # * 가장 많이 등장한 N개 구하기 (Counter.most_common()) # In[8]: from collections import Counter count = Counter(nouns) tags = count.most_common(40) tags[:20] # # 5) WordCloud, matplotlib: 단어 구름 그리기 # * WordCloud 로 워드 클라이우드 이미지 생성 # In[9]: get_ipython().run_line_magic('matplotlib', 'inline') import matplotlib.pyplot as plt from wordcloud import WordCloud font_path = '/usr/share/fonts/truetype/nanum/NanumMyeongjoBold.ttf' wc = WordCloud(font_path=font_path, background_color='white', width=800, height=600) cloud = wc.generate_from_frequencies(dict(tags)) plt.figure(figsize=(10,8)) plt.axis('off') plt.imshow(cloud) # # RSS 워드 클라우드 예제 # In[10]: # 매경경제 증권 draw_wordcloud_from_rss('http://file.mk.co.kr/news/rss/rss_50300009.xml') # In[11]: # 경향신문 IT 과학 부문 draw_wordcloud_from_rss('http://www.khan.co.kr/rss/rssdata/itnews.xml') # In[12]: # 한국경제 주요 뉴스 draw_wordcloud_from_rss('http://rss.hankyung.com/new/news_main.xml') # ### 2017 http://financedata.kr