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( ...
随机推荐
- 什么是EIP、ESP、EBP
堆栈是一种简单的数据结构,是一种只允许在其一端进行插入或删除的线性表.允许插入或删除操作的一端称为栈顶,另一端称为栈底,对堆栈的插入和删除操作被称入栈和出栈.有一组CPU指令可以实现对进程的内存实现堆 ...
- 深入Redis客户端(redis客户端属性、redis缓冲区、关闭redis客户端)
深入Redis客户端(redis客户端属性.redis缓冲区.关闭redis客户端) Redis 数据库采用 I/O 多路复用技术实现文件事件处理器,服务器采用单线程单进程的方式来处理多个客户端发送过 ...
- git 使用和一些错误
一.简单使用 Git是目前世界上最先进的分布式版本控制系统,用于自动记录每次文件的改动,但是和所有版本控制系统一样,只能跟踪文本文件的改动,比如TXT文件,网页,所有的程序代码等,而图片.视频这些二进 ...
- matplotlib 的几种柱状图
1.x 表示数量,y 表示名字 import matplotlib.pyplot as plt dic = {'a': 22, 'b': 10, 'c': 6, 'd': 4, 'e': 2, 'f' ...
- (2)Windows PowerShell使用
什么是PowerShell: Windows PowerShell 是一种命令行外壳程序和脚本环境,使命令行用户和脚本编写者可以利用 .NET Framework 的强大功能.PowerShell是命 ...
- Reverse Subarray To Maximize Array Value
2020-02-03 20:43:46 问题描述: 问题求解: public boolean canTransform(String start, String end) { int n = star ...
- Ruby使用记录
1.首先,重要的事情说三遍,不用在Windows里开发Ruby 1.第一次在windows里安装ruby,装的最新版,当时就遇到了很奇怪的编码问题,如运行命令gem install xxx,提示编码错 ...
- js事件的获取
获取元素样式属性 Method DES clientWidth 获取元素宽度 clientHeight 获取元素高度(内容+内边距) document.body.clientWidth 获取body宽 ...
- @RequestBody和@RequestParam的使用详解
此次分享转载至:https://blog.csdn.net/justry_deng/article/details/80972817 这边文章讲解的比较透彻,主要是在springboot项目中进行使用 ...
- ANTLR随笔(三)
ANTLR基本语法 前面已经简单介绍了ANTLR以及怎么安装和测试. 同学们应该大概清楚ANTLR的使用场景,但是对于关键步骤,怎么编写一个语法文件并没有详细介绍,这篇笔记主要详细讲解一下ANTLR的 ...