人民网军事新闻专区分析
(目标:基于人民网军事新闻的数据收集和整合,建立分类模型)
摘要
本文对人民网军事新闻专区数据集进行探索性数据分析,以可视化、特征相关程度分析等不同方式对其进行分析和整理,并介绍了整理过程中所以到的问题,解决措施等。并将结果分别以词云,柱形图,饼状图和文字的形式呈现出来。此外,完成此项目后的心得也以文字形式呈现。
关键词
python 爬虫 数据处理 分析
目录
代码实现
1.1引入所需包
# -*- coding:utf-8 -*- import requests as re from bs4 import BeautifulSoup as BS import jieba import imageio import wordcloud import matplotlib import matplotlib.pylab as plt import string import csv |
1.2解析网页
#解析网页 def getHtml(url): #传入网页链接 rs = re.get(url) rs.encoding='gbk' #用'gbk'解析 html = rs.text #得到网页内容 return html |
1.3 获得新闻标题和新闻内容
#获得新闻标题 def getComments(html): #传入网页内容 soup = BS(html, 'html.parser') p = soup.find_all('h5') #寻找标签'h5' comments = [] for pi in p: pi = pi.string #得到每一个标签里的字符内容 comments.append(str(pi)) #将得到内容加入列表 return comments #返回题目列表
#获得新闻内容 def getComment(html): #传入网页内容 soup = BS(html, 'html.parser') pp = soup.find_all('em') #寻找标签'em' com = [] for pi in pp: pi=pi.text #得到每一个标签里的内容的文本形式 com.append(str(pi)) #将得到内容加入列表 return com #返回内容列表 |
1.4写入txt文件和读txt文件
#写入txt文件 def wTxt2f(fileName, comments,com): #文件名,题目列表,内容列表 with open(fileName, 'a', encoding='utf-8') as f: for i in ra |