第二章字符串
2.1字符串
str.title()首字母大写
str.upper()大写
str.lower()小写
print("\tpython")添加tab
str.lstrip()删除开头空白
str.rstrip()删除末尾空白
str.strip()删除两端空白
输出单引号和双引号需分来print("one of python's")
2.2数值
3/2 1
3.0/2 1.5
第三章列表
添加元素
list.append()末尾
list.insert(index,'加的值')
删除
del list[0]
list.pop()默认末尾,list.pop(0)第一个元素
list.remove('值')根据值删除元素
list.sort()排序 临时排序可用sorted(list)
list.reverse()翻转列表
第四章操作列表
for i in range(1,5) 1 2 3 4
list = [i**2 for i in range(1.11)] 1 4 9 16 25 36 49 64 81 100
定义元组:tuple = (200,100)元组不可修改
第五章使用if语句处理列表
if elif elif else
第六章字典
遍历:for i in key.items()
获取所有键dict.keys()
获取所有值dict.values()
值以列表形式:dict.setdefault(key,[]).append(value)
第七章 用户输入和while循环
Input从键盘输入
name = input('please enter your name')
print('Hello '+name+'!')
输入默认字符串,使用int()获取数值输入
第八章函数
让实参变成可选,给定一个默认值
def(first,last,middle='')
可以使用切片的方式创建副本list[:]
传递任意数量的实参:需将接收任意数量实参的形参放在最后
def(*toopings) 说明传入的toopings是一个元组
def(**toopings) 说明传入的toopings是一个字典
在给形参制定默认值时,等号两边不要有空格如def function(parameter='value')
第九章 创建类和使用类
class Dog():首字母大写的名称称为类 __init__(self,name,age)是个特殊的方法,self必不可少,且必须位于其他形参前
继承
class ElecticCar(Car):
def __init__(self,make,model,year):
super().__init__(make,model,year)
super()是一个特殊的函数,将父类和子类关联起来,让python调用ElecticCar的父类的方法__init__,让ElecticCar实例包含父类的所有属性。
重写父类的方法
第十章 文件和异常
2.1读取文件
with open(‘1.txt’) as file_object:
contents = file_object.read()
print(contents.rstrip())
read()到达文件末尾时返回一个空的字符串,而将这个空字符串显示出来就是一个空行。
with open():只管打开文件,并在需要时使用,python会自动在合适的时间自动将文件关闭
open() close():需自行关闭,在程序遇到bug时,未运行到close(),文件将不会关闭
2.2逐行读取
with open(‘1.txt’) as file_object:
for line in file_object:
print(line.rstrip())
#lines = file_object.readlines()
#for line in lines:
print()末尾会有一个看不见的换行符
2.3写入文件
with open(‘1.txt’, ‘w’) as file_object:
file_object.write(‘i loev jj.\n’)
file_object.write(‘i loev nn.\n’)
‘a’给文件添加内容,在文件的末尾添加,而不删除文件里的内容
2.4异常
try-except -else
try:
with open(‘1.txt’) as file_object:
contents = file_object.read()
except FileNotFoundError:
print(‘文件不存在’)
else:
word = contents.split()
print(len(words))
2.5存储数据
json.dump(par1,par2) 要存储的数据、用于存储数据的文件对象
json.dumps(par1)转换成json格式
json.load(par1) 下载json文件,读取到内存中
2.6重构
代码能够正确的运行,但可做进一步的改进——将代码划分为一系列完成具体任务的函数
第十一章 测试代码
测试函数
import unittest #引入模块unittest
from name_function import get_formatted_name
class NameTestCase(unittest.TestCase): #创建包含一系列单元测试,并继承unittest.TestCase
def test_first_last_name(self): #必须以test开通,所有以test_开通的方法都将自动运行
formatted_name = get_formatted_name(‘janis’,’joplin’)
self.assertEqual(formatted_name,’Janis Joplin ’)
Unittest.main()
测试类
方法setup()用来创建一个调查对象和一组答案,python会先运行它,再运行以test_开头的方法
第15章 生成数据
15.1绘制图
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签
plt.rcParams['axes.unicode_minus']=False #用来正常显示负号
y = [1,4,9,16,25]
#x = [1,2,3,4,5]
# plt.plot(x,y,linewidth = 5)
plt.plot(y,linewidth = 5)
plt.title('标题',fontsize = 24)
plt.xlabel('x轴名',fontsize = 14)
fig.autofmt_xdate()#绘制斜的日期标签,以免标签彼此重复
plt.ylabel('y轴名',fontsize = 14)
#设置刻度标记大小
plt.tick_params(axis = 'both',labelsize =14)
plt.show()
#plt.savefig('1.png',bbox_inches='tight')#自动保存图表,代替show()
plt.scanner(2,4,s = 200) #绘制某点,并设置尺寸
plt.scanner(x,y,s = 200) #绘制一系列点,并设置尺寸
15.2 自动计算数据
x=list(range(1,1001))
y =[x**2 for i in x]
plt.scanner(x,y,s = 200,edgecolor ='none',c='red')
edgecolor ='none'删除数据点轮廓
c='red'自定义颜色
plt.scanner(x,y,s = 200,edgecolor ='none',c=y,cmap = plt.cm.Blues) 将参数C设置成一个y列表,并使用参数cmap告诉pyplot使用哪个颜色映射
15.3隐藏坐标轴:
plt.axes().get_xaxis().set_visible(False)
plt.axes().get_yaxis().set_visible(False)
15.4调整尺寸
figure指定图表的宽度、高度、分辨率和背景色
plt.figure(dpi=128,figsize(10,6))#figsize绘制窗口尺寸,dpi分辨率
15.5使用pygal模拟掷骰子,绘制直方图
hist = pygal.Bar()#创建一个pygal.Bar()实例,并将其存储在hist中
hist.title = '标题'
hist.x_labels = x轴标签
hist.x_title = 'x标题'
hist.y_title = 'y标题'
hist.add('D6',frequencies)#使用add()将一系列值添加到图表中
hist.render_to_file('visual.svg')将图标渲染成svg文件
第16章 下载数据
16.1 分析csv文件头
import csv
filename = ‘1.csv’
with open(filename) as f:
reader = csv.reader(f)
header_row = next(reader)#返回文件中的下一行,目前第一次调用next,得到的是文件的第一行
for index,header in enumerate(header_row):
print(index,column_header)
highs = []
for row in reader:
highs.append(rows[1])#阅读器对象从其停留的地方继续往下读取csv文件,每次都自动返回当前所处位置的下一行
16.2模块datatime
from datatime import datatime
date = datatime.strptime('2014-7-1','%Y-%m-%d')
2014-07-01 00:00:00
最低温度最高温度存储在一张图中,添加两个数据系列
plt.plot(dates,highs,c='red')
plt.plot(dates,lows,c='blue')
plt.fill_between(dates,highs,lows,facecolor='blue',a=0.1)给图标区域着色
使用try-except-else代码块处理异常
16.3使用pygal绘制折线图
import pygal
#让X轴的日期标签顺时针旋转20°,且不用显示所有的X轴标签
line_chart = pygal.Line(x_label_rotation=20,show_minor_x_labels=False)
line_chart.title = '标题'
dates =[]
close = []
line_chart.x_labels = dates
N = 20
#让X轴坐标每隔20天显示一次
line_chart.x_label_major = dates[::N]
line_chart.add('收盘价',close)
line_chart.render_to_file('折线图.svg')
对数变换可以消除非线性趋势
close_log = [math.log10(_) for _ in close]
line_chart.add('小标签',close)
第17章 使用API
import requests
url = 'https://api.github.com/search/repositories?q=language:python&sort=starts'
r = requests.get(url)
print('status',r.status_code)
#将API响应存储在一个变量中
response_dict = r.json()
print(response_dict.keys())
print('total repositories',response_dict['total_count'])
#探索有关仓库信息
repo_dicts = response_dict['items']
print('repositories returned',len(repo_dicts))
#研究第一个仓库
repo_dict = repo_dicts[0]
print('\nKey:',len(repo_dict))
for key in sorted(repo_dict.keys()):
print(key)
#输出第一个仓库的信息
print('Name',repo_dict['name'])
import requests
import pygal
from pygal.style import LightColorizedStyle as LCS,LightStyle as LS
url = 'https://api.github.com/search/repositories?q=language:python&sort=starts'
r = requests.get(url)
print('status',r.status_code)
#将API响应存储在一个变量中
response_dict = r.json()
# print(response_dict.keys())
print('total repositories',response_dict['total_count'])
# #探索有关仓库信息
repo_dicts = response_dict['items']
names,starts = [], []
for repo_dict in repo_dicts:
names.append(repo_dict['name'])
starts.append(repo_dict['stargazers_count'])
#可视化
my_style = LS('#333366',base_style = LCS)
chart = pygal.Bar(style = my_style,x_label_rotation = 45,show_legend = False)
chart.title='Most started python projects on github'
chart.x_labels =names
chart.add('',starts)
chart.render_to_file('python_repos.svg')