python初学(三)
1.以软科中国最好大学排名为分析对象,基于requests库和bs4库编写爬虫程序,对2015年至2019年间的中国大学排名数据进行爬取,并按照排名先后顺序输出不同年份的前10位大学信息,要求对输出结果的排版进行优化。
import requests
from bs4 import BeautifulSoup class Univ:
def __init__(self, url, num):
self.url=url
self.allUniv=[]
self.num=num def get_htmltext(self):
try:
r=requests.get(self.url,timeout=30)
r.raise_for_status()
r.encoding='utf8'
return r.text
except:
return '' def fillUnivList(self,soup):
data=soup.find_all('tr')
for tr in data:
ltd=tr.find_all('td')
if len(ltd)==0:
continue
singleUniv=[]
for td in ltd:
singleUniv.append(td.string)
self.allUniv.append(singleUniv) def printUnivList(self):
print("{:^4}\t{:^20}\t{:^10}\t{:^8}\t{:^10}\t".format("排名","学校名称","省市","总分","生源质量"))
for i in range(self.num):
u=self.allUniv[i]
if u[0]:
print("{:^4}\t{:^20}\t{:^10}\t{:^8}\t{:^10}\t".format(u[0],u[1],u[2],u[3],u[4]))
else:
print("{:^4}\t{:^20}\t{:^10}\t{:^8}\t{:^10}\t".format(i+1,u[1],u[2],u[3],u[4])) def main(self):
html=self.get_htmltext()
soup=BeautifulSoup(html,'html.parser')
self.fillUnivList(soup)
self.printUnivList() if __name__ == "__main__":
url="http://www.zuihaodaxue.cn/zuihaodaxuepaiming2015_0.html"
print('')
u=Univ(url,10)
u.main()
years=["","","",""]
for year in years:
url="http://www.zuihaodaxue.cn/zuihaodaxuepaiming"+year+".html"
print(year)
u=Univ(url,10)
u.main()
2.豆瓣图书评论数据爬取。在豆瓣图书上自行选择一本书,编写程序爬取豆瓣图书上针对该图书的短评信息,要求:
(1)对不同页码的短评信息均可以进行爬取;
(2)爬取的数据包含用户名、短评内容、评论时间和评分;
能够根据选择的排序方式进行爬取,并针对热门排序,输出前10个短评信息(包括用户名、短评内容、评论时间和评分);
(3)能够根据选择的排序方式进行爬取,并针对热门排序,输出前10个短评信息(包括用户名、短评内容、评论时间和评分);
(4)结合中文分词和词云生成,对前3页的短评内容进行文本分析,并生成一个属于自己的词云图形。
import requests
import re
import jieba
import wordcloud
from bs4 import BeautifulSoup
from fake_useragent import UserAgent class com:
def __init__(self, no,num,page):
self.no=no
self.page=page
self.num=num
self.url=None
self.header=None
self.bookdata=[]
self.txt='' def set_header(self):
ua = UserAgent()
self.header={
"User-Agent":ua.random
} def set_url(self,page):
self.url='https://book.douban.com/subject/{0}/comments/hot?p={1}'.format(str(self.no),str(page+1)) def get_html(self):
try:
r=requests.get(self.url,headers=self.header,timeout=30)
r.raise_for_status()
r.encoding='utf8'
return r.text
except:
return '' def fill_bookdata(self, soup):
commentinfo=soup.find_all('span','comment-info')
pat1=re.compile(r'allstar(\d+) rating')
pat2=re.compile(r'<span>(\d\d\d\d-\d\d-\d\d)</span>')
comments=soup.find_all('span','short')
for i in range(len(commentinfo)):
p=re.findall(pat1,str(commentinfo[i]))
t=re.findall(pat2,str(commentinfo[i]))
self.bookdata.append([commentinfo[i].a.string,comments[i].string,p,t[0]]) def printList(self, num):
for i in range(num):
u=self.bookdata[i]
try:
print("序号: {}\n用户名: {}\n评论内容: {}\n时间:{}\n评分: {}星\n".format(i+1,u[0],u[1],u[3],int(eval(u[2][0])/10)))
except:
print("序号: {}\n用户名: {}\n评论内容: {}\n".format(i+1,u[0],u[1])) def comment(self):
self.set_header()
self.set_url(0)
html=self.get_html()
soup=BeautifulSoup(html,'html.parser')
self.fill_bookdata(soup)
self.printList(self.num) def txtcloud(self):
self.set_header()
for i in range(self.page):
self.bookdata=[]
self.set_url(i)
html=self.get_html()
soup=BeautifulSoup(html,'html.parser')
self.fill_bookdata(soup)
for j in range(len(self.bookdata)):
self.txt+=self.bookdata[j][1]
w=wordcloud.WordCloud(width=1000,font_path="msyh.ttc",height=700,background_color="white")
w.generate(self.txt)
w.to_file("comment.png") def main(self):
self.comment()
self.txtcloud() if __name__ == "__main__":
com(34925415,10,10).main()
3.设
其中,完成下列操作:
(1)在同一坐标系下用不同的颜色和线性绘制y1、y2和y3三条曲线;
import matplotlib.pyplot as plt
import numpy as np x=np.arange(0,360)
y1=x*x
y2=np.cos(x)
y3=y1*y2
plt.plot(x,y1,color='blue')
plt.plot(x,y2,color='red')
plt.plot(x,y3,color='green')
plt.show()
(2)在同一绘图框内以子图形式绘制y1、y2和y3三条曲线。
import matplotlib.pyplot as plt
import numpy as np x=np.arange(0,360)
y1=x*x
y2=np.cos(x)
y3=y1*y2
plt.subplot(311)
plt.plot(x,y1,color='blue')
plt.subplot(312)
plt.plot(x,y2,color='red')
plt.subplot(313)
plt.plot(x,y3,color='green')
plt.show()
4.已知
,在-2<=x<=2区间绘制该分段函数的曲线,以及由该曲线所包围的填充图形。
import matplotlib.pyplot as plt
import numpy as np x=np.arange(-2,2,1e-5)
y1=np.sqrt(2*np.sqrt(np.power(x,2))-np.power(x,2))
y2=-2.14*np.sqrt(np.sqrt(2)-np.sqrt(np.abs(x)))
plt.plot(x,y1,'r',x,y2,'r')
plt.fill_between(x,y1,y2,facecolor='red')
plt.show()

python初学(三)的更多相关文章
- 初学Python(三)——字典
初学Python(三)——字典 初学Python,主要整理一些学习到的知识点,这次是字典. #-*- coding:utf-8 -*- d = {1:"name",2:" ...
- 孤荷凌寒自学python第四十五天Python初学基础基本结束的下阶段预安装准备
孤荷凌寒自学python第四十五天Python初学基础基本结束的下阶段预安装准备 (完整学习过程屏幕记录视频地址在文末,手写笔记在文末) 今天本来应当继续学习Python的数据库操作,但根据过去我自 ...
- Python初学笔记之字符串
一.字符串的定义 字符串是就一堆字符,可以使用""(双引号).''(单引号)来创建. 1 one_str = "定义字符串" 字符串内容中包含引号时,可以使用转 ...
- 学习Python的三种境界
前言 王国维在<人间词话>中将读书分为了三种境界:"古今之成大事业.大学问者,必经过三种之境界:'昨夜西风凋碧树,独上高楼,望尽天涯路'.此第一境也.'衣带渐宽终不悔,为伊消得人 ...
- selenium webdriver (python) 第三版
感谢 感谢购买第二版的同学,谢谢你们对本人劳动成果的支持!也正是你们时常问我还出不出第三版了,也是你们的鼓励,让我继续学习整理本文档. 感谢乙醇前辈,第二版的文档是放在他的淘宝网站上卖的,感谢他的帮忙 ...
- Python第三天 序列 数据类型 数值 字符串 列表 元组 字典
Python第三天 序列 数据类型 数值 字符串 列表 元组 字典 数据类型数值字符串列表元组字典 序列序列:字符串.列表.元组序列的两个主要特点是索引操作符和切片操作符- 索引操作符让我 ...
- 简学Python第三章__函数式编程、递归、内置函数
#cnblogs_post_body h2 { background: linear-gradient(to bottom, #18c0ff 0%,#0c7eff 100%); color: #fff ...
- Python第三天 序列 5种数据类型 数值 字符串 列表 元组 字典 各种数据类型的的xx重写xx表达式
Python第三天 序列 5种数据类型 数值 字符串 列表 元组 字典 各种数据类型的的xx重写xx表达式 目录 Pycharm使用技巧(转载) Python第一天 安装 shell ...
- python selenium 三种等待方式详解[转]
python selenium 三种等待方式详解 引言: 当你觉得你的定位没有问题,但是却直接报了元素不可见,那你就可以考虑是不是因为程序运行太快或者页面加载太慢造成了元素不可见,那就必须要加等待 ...
- python第三十一课--递归(2.遍历某个路径下面的所有内容)
需求:遍历某个路径下面的所有内容(文件和目录,多层级的) import os #自定义函数(递归函数):遍历目录层级(多级) def printDirs(path): dirs=os.listdir( ...
随机推荐
- Red Team 工具集之网络钓鱼和水坑攻击
来自:信安之路(微信号:xazlsec),作者:myh0st 参考项目:https://github.com/infosecn1nja/Red-Teaming-Toolkit 上图是一个 Red Te ...
- Drawing Simple Polygon(Create Simple Polygon from unordered points by angle sorting)
Keywords: 极角排序, Simple Polygon Generation Given set of points in the plane, your task is to draw a p ...
- IDEA上传图片到tomcat服务器上
前端页面: JS代码: //选中图片 var form = document.getElementById("danxuan"); // 用表单来初始化 var formData ...
- 北邮oj 97. 二叉排序树
97. 二叉排序树 时间限制 1000 ms 内存限制 65536 KB 题目描述 二叉排序树,也称为二叉查找树.可以是一颗空树,也可以是一颗具有如下特性的非空二叉树: 若左子树非空,则左子树上所有节 ...
- K:缓存相关问题
缓存的作用在于提高程序的响应速度,一般用于程序存储运算所需数据或程序运算后的结果,以便再次访问或运算相同的程序(数据同样相同)时,能够得到快速的响应(适用于读多写少的场景).在现代计算机体系结构中,根 ...
- 七大Github机器学习热门项目
译者 | 小韩 来源 | analyticsvidhya.com[磐创AI导读]:让我们一起来看下近期热门的机器学习Github仓库,包括了自然语言处理(NLP).计算机视觉(CV)与大数据等多个领域 ...
- Google AI推出新的大规模目标检测挑战赛
来源 | Towards Data Science 整理 | 磐石 就在几天前,Google AI在Kaggle上推出了一项名为Open Images Challenge的大规模目标检测竞赛.当今计算 ...
- TensorFlow系列专题(五):BP算法原理
欢迎大家关注我们的网站和系列教程:http://www.tensorflownews.com/ ,学习更多的机器学习.深度学习的知识! 一.反向传播算法简介 二.前馈计算的过程 第一层隐藏层的计算 第 ...
- 震惊!程序员的福音!不需要敲代码就能完成复杂的逻辑应用? —— Azure Logic App
(大家看完标题可能以为是营销号,哈哈哈哈哈哈哈哈哈...客官请留步, 正经博主....好吧) 今天我们的主题是Azure Logic Apps Azure Logic Apps 是什么? 官方解释:h ...
- LayUI制作日历工作记录簿
标题不知道该如何取,大概就是用Lay UI的Table,制作一个日历,在日历上可以添加每天的工作简记录.记录下LayUI Table的一些用法,一些值得探索的地方在于日历生成后,给周末加背景色,当天加 ...