43张正杰

导航

一个完整的大作业-----新浪新闻

1.选一个自己感兴趣的主题。

2.网络上爬取相关的数据。

3.进行文本分析,生成词云。

4.对文本分析结果解释说明。

5.写一篇完整的博客,附上源代码、数据爬取及分析结果,形成一个可展示的成果。

 

1、最近对国际新闻比较感兴趣,并且希望看看国际新闻的热点地区等,于是乎我找到了新浪新闻的国际版快。(http://news.sina.com.cn/world/)

在浏览器中按F12进入查看器并且选取新闻标题定位

 

2.网络上爬取相关的数据。

import requests
from bs4 import BeautifulSoup

url = 'http://news.sina.com.cn/china/'
res = requests.get(url)
# 使用UTF-8编码
res.encoding = 'UTF-8'

# 使用剖析器为html.parser
soup = BeautifulSoup(res.text, 'html.parser')

#遍历每一个class=news-item的节点
for news in soup.select('.news-item'):
    h2 = news.select('h2')
    #只选择长度大于0的结果
    if len(h2) > 0:
        #新闻时间
        time = news.select('.time')[0].text
        #新闻标题
        title = h2[0].text
        #新闻链接
        href = h2[0].select('a')[0]['href']
        #打印
        print(time, title, href)

输出后获得新闻标题:

 

3.进行文本分析,生成词云。

# -*- coding: utf-8 -*-  
from os import path  
from scipy.misc import imread    
import jieba  
import sys  
import matplotlib.pyplot as plt  
from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator    
text = open('D:\\news.txt').read()  
wordlist = jieba.cut(text)     #cut_all = True  
wl_space_split = " ".join(wordlist)  
#print wl_space_split 
d = path.dirname(__file__)  
nana_coloring = imread(path.join(d, "D:\\1.jpg"))  
my_wordcloud = WordCloud( background_color = 'white',    
                            mask = nana_coloring,         
                            max_words = 2000,            
                            stopwords = STOPWORDS,  
                            max_font_size = 50,        
                            random_state = 30,            )  
 # generate word cloud   
text_dict = {   'you': 2993,   'and': 6625,   'in': 2767,   'was': 2525,   'the': 7845,}
my_wordcloud = WordCloud().generate_from_frequencies(text_dict)
#my_wordcloud.generate(text_dict)  
# 给词添加颜色
image_colors = ImageColorGenerator(nana_coloring)  
# 重新给颜色给词  
my_wordcloud.recolor(color_func=image_colors)  
plt.imshow(my_wordcloud)    
plt.axis("off")             
plt.show()  
# 保存图片   
my_wordcloud.to_file(path.join(d, "cloudimg.png"))  

生成云图:

由此可见在近期的国际新闻中,有关美国、英国等大国任是主要的热点国家,特朗普也是主要的热点词语。

 

4.对文本分析结果解释说明。

import requests
from bs4 import BeautifulSoup
url = 'http://news.sina.com.cn/china/'
res = requests.get(url)
# 使用UTF-8编码
res.encoding = 'UTF-8'
# 使用剖析器为html.parser
soup = BeautifulSoup(res.text, 'html.parser')

指定网站的url 并使用BesutifulSoup4

#遍历每一个class=news-item的节点
for news in soup.select('.news-item'):
    h2 = news.select('h2')
    #只选择长度大于0的结果
    if len(h2) > 0:
        #新闻时间
        time = news.select('.time')[0].text
        #新闻标题
        title = h2[0].text
        #新闻链接
        href = h2[0].select('a')[0]['href']
        #打印
        print(time, title, href)

遍历每一个相关元素是.news-item, 并且是<h2>标签的信息。然后使用条件语句,如果<h2>字符大于2的就把时间和标题的连接分别定于给time 和title.最后输出结果。

 

posted on 2017-10-31 09:35  43张正杰  阅读(182)  评论(0编辑  收藏  举报