又到一年总结季,下周要考Python啦,整理一下老师给的ppt
if
这样的结构都不支持将一些函数或变量封装在.py
文件中,以供调用
比函数更高层次的封装
.py
文件的名字就是模块的名字
通过这种封装,可以避免单个.py
文件过长
自定义的模块应该放在主程序目录下
模块被载入后成为了一个对象
模块的意义:代码重用和管理(同函数);模块提供命名空间(作为对象来实现)
#打开一个文件
input = open(‘file_name’, ‘r’)
#读取文件中的内容到一个字符串
content = input.read()
#关闭文件
input.close()
r‘xxx’
line=input.readline()
lines=input.readlines()
#以写入方式打开一个文件
output = open(‘file_name’, ‘w’)
#写入一行
output.write(‘one apple a day’ + ‘\n’)
#关闭文件
output.close()
class 你的类:
xxx
xxx
self
——对象自己super
(类名称,self)——父类o1=C1()
o2=C1()
class 类的名字(父类的名字):
xxx
xxx
class C1(C2,C3):......
__init__()
pip install ipython
ipython
输入?
查看帮助文档import math
math.[Tab]
ctrl + C
退出运行-按↑可以调出上一条指令
%run D:/test.py
%cpaste
命令来执行多行代码%paste
命令来执行当前剪贴板中的内容pip install numpy
安装import numpy as np
来载入d=[1,2,3]
arr=np.array(d)
arr1 = np.array([1,2,3], dtype = np.float64)
arr2 = np.array([1,2,3], dtype = np.int32)
.copy()
pip install scipy
安装Series
和DataFrame
两种数据结构,以及相应的方法from pandas import Series,DataFrame
import pandas as pd
obj2 = Series([2,2,3,3], index = [‘a’, ‘b’, ‘c’, ‘d’])
d = {‘a’:123, ‘b’:456, ‘c’ :789}
obj3 = Series(d)
states = [‘a’, ‘c’, ‘d’]
d = {‘name’: [‘Bob’, ‘Jack’, ‘Lili’, ‘Dongwei’],
‘age’: [28, 33, 22, 88],
‘salary’:[3000, 2, 5000, 999999999]}
frame1 = DataFrame(d)
frame2 = DataFrame(d, columns = [‘age’, ‘name’, ‘salary’])
frame3 = DataFrame(d, index = [‘01’, ‘02’, ‘03’, ’04’])
frame3[‘IQ’] = [110, 70, 100, 999] #长度必须匹配
somebody = frame3.ix[’02’]
frame4 = frame3.drop(‘IQ’, axis = 1) #丢弃列
frame5 = frame3.drop(’02’)
s = Series([1,2,3])
frame5.insert(1, ‘aaa’, s)
append #连接
difference #差集
intersection #交集
union #并集
frame6 = frame3[frame3[‘age’] > 30]
obj6 = obj3.sort_index()
frame 10 = frame3. sort_index()
frame 11 = frame3. sort_index(axis = 1)
手工产生NaN值:np.nan
x2 = x.dropna() #剔除含NaN的行
x2 = x.fillna(0) #以0替换NaN
x2 = x.fillna({‘a’:-1, ‘c’:0}) #对于’a’列’c’列分别操作
x2 = x.fillna(method = ‘ffill’) # 以插值替换NaN
s1 = frame3.sum() #按列小计
s2 = frame3.sum(axis = 1) #按行
np.save(文件名,矩阵)
np.load(文件名)
pd.read_csv(文件名)#读取csv表格,自动类型推断
frame.to_csv(文件名)
frame.save(文件名)
pd.load(文件名)
xls_file = pd.ExcelFile(‘data.xls’)
table = xls_file.parse(‘Sheet1’)
from lxml import objectify
parsed = objectify.parse(open('cd_catalog.xml'))
root=parsed.getroot()
from lxml.html import parse
from urllib.request import urlopen
parsed = parse(urlopen('http://www.zufe.edu.cn/’))
doc = parsed.getroot()
links = doc.findall('.//a’)
links[0].get('href’)
links[0].text_content()
parsed = parse(urlopen('http://info.zufe.edu.cn/xygk/szdw.htm’))
doc = parsed.getroot()
tables = doc.findall(‘.//table’)
‘.//tr’ ‘.//td’
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.plot(np.arange(10))
fig.show()
ax1 = fig.add_subplot(2,2,1)
ax2 = fig.add_subplot(2,2,2)
ax3 = fig.add_subplot(2,2,3)
#参数:行数,列数,第几个
fig.subplots_adjust(wspace = 0.5)
#可用参数:left right bottom top wspace hspace
from numpy.random import randn
ax1.plot(randn(50).cumsum())#折线图
ax2.hist(randn(100), bins = 20)#柱状图
ax3.scatter(randn(50), randn(50))#散点图
fig.show()
ax1.plot(randn(50).cumsum(), linestyle = ‘--’, color = ‘g’, marker = ‘o’ )
ax1.set_xlim([0,100])
ax1.set_ylim([-1,1])
ticks = ax1.set_xticks([0,20,40,60,80,100])
labels = ax1.set_xticklabels([‘zero’, ‘one’, ‘two’, ‘three’, ‘four’, ‘five’], rotation = 30)
ax1.set_title('fig 1’)
ax1.set_xlabel(‘Step’)
ax1.set_ylabel(‘Value’)
fig.show()
ax4 = fig.add_subplot(2,2,4)
ax4.plot(randn(1000).cumsum(), ‘k’, label = ‘one’)
ax4.plot(randn(1000).cumsum(), ‘r.’, label = ‘two’)
ax4.legend(loc = ‘best’)
fig.show()
rect = plt.Rectangle((0.2,0.75), 0.4, 0.15, color = ‘g’, alpha = 0.2)
ax.add_patch(rect)
fig.savefig(‘xxx.svg’, dpi = 400, bbox_inches = ‘tight’)
from pandas import Series, DataFrame
import pandas as pd
df = DataFrame(randn(10,4).cumsum(0), columns = [‘A’, ‘B’, ‘C’, ‘D’], index = np.arrange(0,100,10))
df.plot()
import scipy.io as sio
raw_K=sio.loadmat('Subject1K.mat')
raw_V=sio.loadmat('Subject1V.mat')
k = raw_K['Subject1K']
v = raw_V['Subject1V']
pip install pyqt5
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class Form(QDialog):
def __init__(self,parent=None):
super().__init__(parent)
app=QApplication(sys.argv)
form=Form()
form.show()
app.exec_()
import sys
from math import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class Form(QDialog):
def __init__(self, parent=None):
super().__init__(parent)
self.text = QLabel('AAA')
self.browser = QTextBrowser()
self.lineedit = QLineEdit("Type an expression.")
self.lineedit.selectAll()
layout = QVBoxLayout()
layout.addWidget(self.text)
layout.addWidget(self.browser)
layout.addWidget(self.lineedit)
self.setLayout(layout)
self.lineedit.setFocus()
self.lineedit.returnPressed.connect(self.updateUi)
self.setWindowTitle("Calculate")
def updateUi(self):
try:
text = str(self.lineedit.text())
self.browser.append("%s = %s" % (text, eval(text)))
except:
self.browser.append("%s is invalid!" % text)
app = QApplication(sys.argv)
form = Form()
form.show()
app.exec_()
import sys
import urllib.request
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class Form(QDialog):
def __init__(self, parent=None):
super().__init__(parent)
date = self.getdata()
rates = sorted(self.rates.keys())
dateLabel = QLabel(date)
self.fromComboBox = QComboBox()
self.fromComboBox.addItems(rates)
self.fromSpinBox = QDoubleSpinBox()
self.fromSpinBox.setRange(0.01, 10000000.00)
self.fromSpinBox.setValue(1.00)
self.toComboBox = QComboBox()
self.toComboBox.addItems(rates)
self.toLabel = QLabel("1.00")
grid = QGridLayout()
grid.addWidget(dateLabel, 0, 0)
grid.addWidget(self.fromComboBox, 1, 0)
grid.addWidget(self.fromSpinBox, 1, 1)
grid.addWidget(self.toComboBox, 2, 0)
grid.addWidget(self.toLabel, 2, 1)
self.setLayout(grid)
self.fromComboBox.currentIndexChanged.connect(self.updateUi)
self.toComboBox.currentIndexChanged.connect(self.updateUi)
self.fromSpinBox.valueChanged.connect(self.updateUi)
self.setWindowTitle("Currency")
def updateUi(self):
to = self.toComboBox.currentText()
from_ = self.fromComboBox.currentText()
amount = ((self.rates[to]/self.rates[from_])*self.fromSpinBox.value())
self.toLabel.setText("{0:.2f}".format(amount))
def getdata(self):
self.rates = {}
try:
date = "Unknown"
data = urllib.request.urlopen("https://www.gov.uk"
"/government/uploads/system/uploads"
"/attachment_data/file/702273"
"/exrates-monthly-0518.csv").read()
for line in data.decode("utf-8", "replace").split("\n"):
line = line.rstrip()
if not line or line.startswith(("#", "Closing ", "Country")):
continue
fields = line.split(",")
if line.startswith("China"):
date = fields[-1]
else:
try:
value = float(fields[3])
self.rates[fields[0]] = value
except ValueError:
pass
return "Exchange Rates Date: " + date
except Exception as e:
return "Failed to download:\n{}".format(e)
app = QApplication(sys.argv)
form = Form()
form.show()
app.exec_()
self. aLabel = QLabel(self)
self. aLabel. setText(“AAA”)
self. aLabel.setPixmap( QPixmap(“a.jpg"))
self.mySpinBox = QDoubleSpinBox(self)
self.mySpinBox. setRange(1, 1000000000)
self.mySpinBox.setValue(1000)
self.mySpinBox.valueChanged.connect(self.updateUi)
设置:setMinimum,setMaximum,setSingleStep,setValue
信号:valueChanged
读取:v = self.mySlider.value()
self.lineedit = QLineEdit("Type a string.")
self.lineedit.returnPressed.connect(self.updateUi)
s = self.lineedit.Text()
self.browser = QTextBrowser()
self.browser.append(‘aaa’)
self.listWidget = QListWidget(self)
self.listWidget.addItems(['item1', 'item2', 'item3'])
self.listWidget.itemClicked.connect(self.XXX)
self.comboBox = QComboBox(self)
itemdata = ['item0', 'item1', 'item2']
self.comboBox.addItems(itemdata)
self.comboBox.currentIndexChanged.connect(self.updateUi)
self.okButton = QPushButton(self)
self.okButton. setText(“OK")
self.okButton.clicked.connect(self.accept)
self.layout = QVBoxLayout(self)
self.layout.addWidget(xxx)
self.setLayout(layout)
self.layout = QGridLayout(self)
self.layout.addWidget(myLabel, 0, 0)
self.layout.addWidget(mySpinBox, 0, 0)
self.setLayout(layout)
s = QSpacerItem(20, 20, QSizePolicy.Minimum, QSizePolicy.Expanding)
layout.addSpacerItem(s)
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class PenPropertiesDlg(QDialog):
def __init__(self, parent=None):
super(PenPropertiesDlg, self).__init__(parent)
widthLabel = QLabel("&Width:")
self.widthSpinBox = QSpinBox()
widthLabel.setBuddy(self.widthSpinBox)
self.widthSpinBox.setAlignment(Qt.AlignRight|Qt.AlignVCenter)
self.widthSpinBox.setRange(0, 24)
self.beveledCheckBox = QCheckBox("&Beveled edges")
styleLabel = QLabel("&Style:")
self.styleComboBox = QComboBox()
styleLabel.setBuddy(self.styleComboBox)
self.styleComboBox.addItems(["Solid", "Dashed", "Dotted", "DashDotted", "DashDotDotted"])
okButton = QPushButton("&OK")
cancelButton = QPushButton("Cancel")
buttonLayout = QHBoxLayout()
buttonLayout.addStretch()
buttonLayout.addWidget(okButton)
buttonLayout.addWidget(cancelButton)
layout = QGridLayout()
layout.addWidget(widthLabel, 0, 0)
layout.addWidget(self.widthSpinBox, 0, 1)
layout.addWidget(self.beveledCheckBox, 0, 2)
layout.addWidget(styleLabel, 1, 0)
layout.addWidget(self.styleComboBox, 1, 1, 1, 2)
layout.addLayout(buttonLayout, 2, 0, 1, 3)
self.setLayout(layout)
self.setWindowTitle("Pen Properties")
okButton.clicked.connect(self.accept)
cancelButton.clicked.connect(self.reject)
class Form(QDialog):
def __init__(self, parent=None):
super(Form, self).__init__(parent)
self.width = 1
self.beveled = False
self.style = "Solid"
penButton = QPushButton("Set Pen")
self.label = QLabel("The Pen has not been set")
self.label.setTextFormat(Qt.RichText)
layout = QVBoxLayout()
layout.addWidget(penButton)
layout.addWidget(self.label)
self.setLayout(layout)
self.setWindowTitle("Pen")
penButton.clicked.connect(self.setPenProperties)
self.updateData()
def updateData(self):
bevel = ""
if self.beveled:
bevel = "
Beveled"
self.label.setText("Width = {}
Style = {}{}".format(self.width, self.style, bevel))
def setPenProperties(self):
dialog = PenPropertiesDlg(self)
dialog.widthSpinBox.setValue(self.width)
dialog.beveledCheckBox.setChecked(self.beveled)
dialog.styleComboBox.setCurrentIndex(
dialog.styleComboBox.findText(self.style))
if dialog.exec_():
self.width = dialog.widthSpinBox.value()
self.beveled = dialog.beveledCheckBox.isChecked()
self.style = dialog.styleComboBox.currentText()
self.updateData()
app = QApplication(sys.argv)
form = Form()
form.resize(400, 200)
form.show()
app.exec_()
image = QImage(fname)
imageLabel = QLabel()
imageLabel.setPixmap(QPixmap.fromImage(image))
pip3 install PyQt5_tools
pyuic5 -o 1.py 1.ui
大概就是这样了,下周上机考了1551
书于吃了玉米水饺就不会冻耳朵的冬至
12.24
今天考完了Python,无语了,好难啊,我是废物,1551
pip install Python的沉重打击
successfully installed
并不愉快地打出gg