Python笔记

Installing Python 3 - How to install/use both Python 2 and Python 3   https://www.youtube.com/watch?v=IX6mc9l6tY4&index=2&list=PLQVvvaa0QuDe8XSftW-RAxdo6OmaeL85M
python官网: www.python.org

开始>python shell窗口 输入print('hi')
print('Hi',5) #输出Hi5
print('we\'re going to the store') #\后字符原样输出
print('Hi'+str(5)) #str()方法, int('8')
4**4 #输出256, 表示4的4次方

x,y = (3,8) #x=3, y=8
for eachNumber in exampleList  #相当于c#中的foreach

rang(1,11) #输出1到10
格式化字符串函数format: "苹果的花费为:{};葡萄的话费为:{};总花费为:{}".format(apple_cost,grape_cost,total_cost)
变量交换值: 
a = 10
b = 20
a, b = b, a #结果为a is 20, b is 10

if z<y>x:
    print('y is greater than z and greater than x')

if x>y:
    print('111')
elif x<z:    #elif, else if的写法
    print('222')
else:
    print('333')

def simple(num1,num2=5):
    print(num1,num2)
simple(2)  #输出2 5, num2默认值为5,方法中可以只传一个没有默认值的参数

有多个默认值参数,调用方法: basic_window(500,350,bgc='b')

Python 3 Programming Tutorial - Global and Local Variables    https://www.youtube.com/watch?v=r9LtArXOYjk&index=14&list=PLQVvvaa0QuDe8XSftW-RAxdo6OmaeL85M
使用全局变量需要在方法里面声明:
x=6
def example():
    global x  #这里声明x为全局变量
    print(x)
    x+=5
    print(x)

Python 3 Programming Tutorial - Installing modules  https://www.youtube.com/watch?v=UKXx4e9PotI&index=15&list=PLQVvvaa0QuDe8XSftW-RAxdo6OmaeL85M
Python Extension Packages: www.lfd.uci.edu/~gohlke/pythonlibs/
PyQtGraph: www.pyqtgraph.org 下载pyqtgraph-0.9.8.tar.gz解压, 文件夹右键打开命令窗口执行setup.py install(有setup.py文件).

How to download and install Python Packages and Modules with Pip    https://www.youtube.com/watch?v=jnpC_Ib_lbc&list=PLQVvvaa0QuDe8XSftW-RAxdo6OmaeL85M&index=16
使用指定的Python版本: C:/Python34/Scripts/pip install matplotlib
PyPI - the Python Package Index: https://pypi.python.org/pypi
https://www.lfd.uci.edu/~gohlke/pythonlibs/ 下载所需的package(.whl), 打开命令窗口输入pip install "xxx.whl"

print('\n') #\n换行

readMe = open('exampleFile.txt','r').readlines()  #这里的readlines()返回数组如['111','222','333'], 如果是read()方法则返回字符串
print(readMe)

if __name__ == '__main__': #如果是执行的本脚本则会打印test,如果是执行的其他脚本引用了本脚本则不会打印test
    print('test')

Getting user input:
x = input('What is your name?')
print('Hello',x)

Python 3 Programming Tutorial - Statistics (Mean, Standard Deviation)   https://www.youtube.com/watch?v=D2U6yg0i-oA&index=24&list=PLQVvvaa0QuDe8XSftW-RAxdo6OmaeL85M
自身模块存放路径: C:/Python/Lib, 第三方package存放路径: C:/Python/Lib/site-packages

import statistics
example_list = [4,2,3,5]
x = statistics.variance(example_list)
print(x)

as:
import statistics as s
x = s.variance(example_list)

连简写都不要:
from statistics import variance
x = variance(example_list)

Python 3 Programming Tutorial - Lists and Tuples    https://www.youtube.com/watch?v=RVXIBZvg-W8&index=27&list=PLQVvvaa0QuDe8XSftW-RAxdo6OmaeL85M
Tuples不能变,List可以变.
Tuples:
x = 5,6,7
x = (5,6,7)
print(x[1])  #输出6

List: 
y = [5,6,7,8]

Python 3 Programming Tutorial - List Manipulation   https://www.youtube.com/watch?v=LUoKlnK5wcc&list=PLQVvvaa0QuDe8XSftW-RAxdo6OmaeL85M&index=28
x = [5,7,3,4]
x.append(2)  #将2加到list的最后
x.insert(2,99)  #插入到index为2的位置,值是99
x.remove(2) #移除第一个元素为2的元素
x.remove(x[2]) #移除第三个元素
print(x[2:3]) #输出第3到第四个元素, 结果为[3,4]
print(x[-1]) #输出最后一个元素
print(x[-2]) #输出倒数第二个元素
print(x.index[7]) #输出元素7的序列号,结果为1
print(x.count[7]) #输出有多少个元素7, 结果为1
x.sort()

Python 3 Programming Tutorial - Multi-dimensional List  https://www.youtube.com/watch?v=Go-FfGhxbSM&list=PLQVvvaa0QuDe8XSftW-RAxdo6OmaeL85M&index=29
x = [[5,6],[6,7],[7,2],[2,5]]
print(x[1][0])  #第二个元素里面的第一个元素, 结果为6

Python 3 Programming Tutorial - Reading from a CSV spreadsheet    https://www.youtube.com/watch?v=K_oXb04izZM&list=PLQVvvaa0QuDe8XSftW-RAxdo6OmaeL85M&index=30
import csv
with open('example.csv') as csvfile:
    readCSV = csv.reader(csvfile, delimiter=',')
    for row in readCSV:
        print(row) 
        
Python 3 Programming Tutorial - Try and Except error Handling  https://www.youtube.com/watch?v=nqGhjLUhyDc&index=31&list=PLQVvvaa0QuDe8XSftW-RAxdo6OmaeL85M
try:
    ...
except Exception as e:
    print(e)
    
if whatColor in colors:   #if in    

Python 3 Programming Tutorial - Multi-line Print  https://www.youtube.com/watch?v=gINlrLx2zNA&list=PLQVvvaa0QuDe8XSftW-RAxdo6OmaeL85M&index=32
print('''
aaa
bbb
ccc
''')

Python 3 Programming Tutorial - Dictionaries   https://www.youtube.com/watch?v=YNRc6c0wUA8&list=PLQVvvaa0QuDe8XSftW-RAxdo6OmaeL85M&index=33
exDict = {'Jack':15, 'Bob':22, 'Alice':12, 'Kevin':17}
exDict['Tim'] = 14  #添加
exDict['Tim'] = 15  #修改
del exDict['Tim']  #删除

Python 3 Programming Tutorial - Built-in Functions  https://www.youtube.com/watch?v=7rjJrQy9gi4&list=PLQVvvaa0QuDe8XSftW-RAxdo6OmaeL85M&index=34
exNum1 = -5
print(abs(exNum1))  #结果为5
help()  #ctrl + c退出
max(exList) #max函数
alt + p #输出上一次打印的东西
int('55')
str(55)

Python 3 Programming Tutorial - OS Module  https://www.youtube.com/watch?v=wgHeTJtth0w&index=35&list=PLQVvvaa0QuDe8XSftW-RAxdo6OmaeL85M
import os
curDir = os.getcwd() #get current working directory
os.mkdir('newDir')
import time
time.sleep(2)
os.rename('newDir','newDir2')
tiem.sleep(2)
os.rmdir('newDir2')

help(os)

Python 3 Programming Tutorial - Sys Module   https://www.youtube.com/watch?v=rLG7Tz6db0w&index=36&list=PLQVvvaa0QuDe8XSftW-RAxdo6OmaeL85M
import sys
sys.stderr.write('This is stderr text\n')  #红色的文字
sys.stderr.flush()
sys.stdout.write('This is stdout text\n')  #蓝色的文字
print(sys.argv)

文件夹右键打开命令窗口执行python sys.py(sys.py是python文件),即是执行这个python文件中的代码.

Python 3 Programming Tutorial - urllib module  https://www.youtube.com/watch?v=5GzVNi0oTxQ&list=PLQVvvaa0QuDe8XSftW-RAxdo6OmaeL85M&index=37
urllib module用于访问网络

import urllib.request
import urllib.parse
#x = urllib.request.urlopen('https://www.google.com')
#print(x.read()) #打印google页面的源代码
url="http://pythonprogramming.net"
values={'s':'basic','submit':'search'}  #网址后面所带的参数
data=urllib.parse.urlencode(values)
data=data.encode('utf-8')
req=urllib.request.Request(url,data)
resp=urllib.request.urlopen(req)
respData=resp.read()
print(respData)

Python 3 Programming Tutorial - Regular Expressions / Regex with re    https://www.youtube.com/watch?v=sZyAn2TW7GY&list=PLQVvvaa0QuDe8XSftW-RAxdo6OmaeL85M&index=38
import re #导入正则表达式的命名空间

#注意变量右边是三个单引号
exampleString = '''  
Jessica is 15 years old, and Daniel is 27 years old.
Edward is 97, and his grandfather, Oscar, is 98.
'''
ages = re.findall(r'\d{1,3}',exampleString)
names = re.findall(r'[A-Z][a-z]*', exampleString)

print(ages)
print(names)

ageDict = {}
x=0
for eachName in names:
    ageDict[eachName] = ages[x]  #相当于赋值给属性
    x+=1
print(ageDict)  #结果为 {'Daniel':'27','Jessica':'15',...}

Python 3 Programming Tutorial - Parsing Websites with re and urllib   https://www.youtube.com/watch?v=GEshegZzt3M&list=PLQVvvaa0QuDe8XSftW-RAxdo6OmaeL85M&index=39
import urllib.request
import urllib.parse
import re
url = 'http://pythonprogramming.net'
values = {'s':'basics','submit':'search'}
data = urllib.parse.urlencode(values)
data = data.encode('utf-8')
req = urllib.request.Request(url,data)
resp = urllib.request.urlopen(req)
respData = resp.read()
print(respData)
paragraphs=re.findall(r'<p>(.*?)</p>',str(respData))
for eachP in paragraphs:
    print(eachP)

Python 3 Programming Tutorial - tkinter module making windows   https://www.youtube.com/watch?v=Ccct5D2AyNM&list=PLQVvvaa0QuDe8XSftW-RAxdo6OmaeL85M&index=40
image的libery: 打开www.lfd.uci.edu/~gohlke/pythonlibs/ 页面搜索pillow, 打开www.lfd.uci.edu/~gohlke/pythonlibs/#pil,下载Pillow-2.5.1.win-amd64-py3.4.exe
from tkinter import *
from PIL import Image, ImageTk
class Window(Frame):  #Frame来自tkinter
    def __init__(self,master = None):
        Frame.__init__(self,master)
        self.master=master
        self.init_window()
    def init_window(self):
        self.master.title("GUI")
        self.pack(fill=BOTH, expand=1)
        #quitButton = Button(self, text="Quit",command=self.client_exit) #Button来自tkinter
        #quitButton.place(x=0,y=0)
        menu = Menu(self.master)
        self.master.config(menu=menu)
        
        file = Menu(menu)
        file.add_command(label='Exit',command=self.client_exit)  #如果self.client_exit后面加上括号(),则会立即执行改方法
        menu.add_cascade(label='File',menu=file)
        
        edit=Menu(menu)
        edit.add_command(label='Show Image', command=self.showImg)
        edit.add_command(label='Show Text', command=self.showTxt)
        menu.add_cascade(label='Edit',menu=edit)
        
    def showImg(self):
        load=Image.open('pic.png')
        render=imageTk.PhotoImage(load)
        
        img=Label(self,image=render)
        img.image=render
        img.place(x=0,y=0)
        
    def showTxt(self):
        text = Label(self, text='Hey there good lookin!')
        text.pack()
        
        
    def client_exit(self):
        exit()
root = Tk()
root.geometry("400*300")
app = Window(root)
root.mainloop()

Python 3 Programming Tutorial - Threading module  https://www.youtube.com/watch?v=NwH0HvMI4EA&index=45&list=PLQVvvaa0QuDe8XSftW-RAxdo6OmaeL85M
import threading
from queue import Queue
import time
print_lock = threading.Lock()
def exampleJob(worker):
    time.sleep(0.5)
    with print_lock:
        print(threading.current_thread().name, worker)
        
def threader():
    while True:
        worker=q.get()
        exampleJob(worker)
        q.task_done()
        
q = Queue()

for x in rang(10):    
    t = threading.Thread(target  = threader)
    t.daemon = True
    t.start()
    
start = time.time()

for worker in rang(20):    
    q.put(worker)
    
q.join()

print('Entire job took:',time.time()-start)    

Python 3 Programming Tutorial - cx freeze python to exe  https://www.youtube.com/watch?v=GSoOwSqTSrs&index=46&list=PLQVvvaa0QuDe8XSftW-RAxdo6OmaeL85M
cx freeze将程序打包成exe文件,网址: cx-freeze.sourceforge.net, 使用命令行或者下载安装cx_Freeze-4.3.3.win-amd64-py3.4.exe (md5)
setup.py:
from cx_Freeze import setup, Executable
setup(name='urlParse',
    version='0.1',
    description='Parse stuff',
    executables=[Executable("distme.py")]
    )
打开命令窗口,cd到setup.py文件位置,执行命令: python setup.py build, 会创建一个build文件夹里面包含生成的exe文件和运行所依赖的环境文件.

Python 3 Programming Tutorial - Subprocess module  https://www.youtube.com/watch?v=5XU-mAZVv4w&index=47&list=PLQVvvaa0QuDe8XSftW-RAxdo6OmaeL85M
communicate from script to shell and get output from the shell.

python
import subprocess
subprocess.call('python systut.py "check this out!"',shell=True)  #输出check this out!

Python 3 Programming Tutorial - Matplotlib Graphing Intro   https://www.youtube.com/watch?v=H72jSxkLQHQ&index=48&list=PLQVvvaa0QuDe8XSftW-RAxdo6OmaeL85M
官网: matplotlib.org/index.html 下载, 或者打开www.lfd.uci.edu/~gohlke/pythonlibs/页面搜索matplotlib 下载安装.
from matplotlib import pyplot as plt
from matplotlib import style  #下载style.zip: pythonprogramming.net/downloads/style.zip, 将style文件夹放入项目根目录下.
style.use('ggplot')

x = [5,6,7,8]
y = [7,3,8,3]
plt.grid(True, color='k')
#plt.scatter(x,y,color='c',align='center') 点状图
#plt.bar(x,y,color='c',align='center') 柱状图
plt.plot(x,y,'g',linewidth=5, label='Line One')  #'g'代表线的颜色是绿色,5表示线的粗细, label线的备注.

plt.title('Epic Chart')
plt.ylabel('Y axis')
plt.xlabel('X axis')
plt.legend() #跟上面的label='Line One'配套出现

plt.show() #打开一个图形窗口

Python 3 Programming Tutorial - Matplotlib plotting from a CSV  https://www.youtube.com/watch?v=MNLmQJtCCZY&list=PLQVvvaa0QuDe8XSftW-RAxdo6OmaeL85M&index=53
from matplotlib import pyplot as plt
from matplotlib import style
import numpy as np
style.use('ggplot')
x,y = np.loadtxt('exampleFile.txt',unpack=True,delimiter=',')
plt.plot()
plt.title('Epic Chart')
plt.ylabel('Y axis')
plt.xlabel('X axis')
plt.show() 

Python 3 Programming Tutorial - ftplib FTP transfers Python   https://www.youtube.com/watch?v=QVyAeM12wVY&list=PLQVvvaa0QuDe8XSftW-RAxdo6OmaeL85M&index=54
from ftplib import FTP
ftp = FTP('domainname.com')
ftp.login(user='usernamae', passwd='password')
ftp.cwd('/specificdomain-or-location/')  #cwd means change working directory

def grabFile():
    filename = 'fileName.txt'
    localfile = open(filename,'wb')
    ftp.retrbinary('RETR '+filename, localfile.write, 1024)
    ftp.quit()
    localfile.close()
    
def placeFile():
    filename = 'fileName.txt'
    ftp.storbinary('STOR '+filename, open(filename, 'rb'))
    ftp.quit()
    
Python 3 Programming Tutorial - Sockets intro   https://www.youtube.com/watch?v=wzrGwor2veQ&index=55&list=PLQVvvaa0QuDe8XSftW-RAxdo6OmaeL85M
import socket
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
print(s)
server='pythonprogramming.net'
port=80
server_ip = socket.gethostbyname(server)
print(server_ip)
request="GET / HTTP/1.1\nHost: "+server+"\n\n"
s.connect((server,port))
s.send(request.encode())
result = s.recv(4096)
#print(result)
while(len(result)>0):
    print(result)
    result = s.recv(1024)
    
Python 3 Programming Tutorial - Sockets simple port scanner  
import socket
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server='pythonprogramming.net'
def pscan(port):
    try:
        s.connect((server,port))
        return True
    except:
        return False

for x in range(1,26):   #rang(1,26) means 1~25
    if pscan(x):
        print('Port',x,'is open')
    else:
        print('Port',x,'is closed')
        
Python 3 Programming Tutorial - Threaded port scanner  https://www.youtube.com/watch?v=icE6PR19C0Y&index=57&list=PLQVvvaa0QuDe8XSftW-RAxdo6OmaeL85M
import socket
import threading
from queue import Queue

print_lock = threading.Lock()
target = 'pythonprogramming.net'

def portscan(port):
    s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    try:
        con = s.connect((target,port))
        with print_lock:
            print('port',port,'is open!')
        con.close()
    except:
        pass

def threader():
    while True:
        worker = q.get()
        portscan(worker)
        q.task_done()
        
q = Queue()        

for x in range(30):
    t = threading.Thread(target=threader)
    t.daemon = True
    t.start()

for worker in range(1,101):
    q.put(worker)
q.join()    

Python 3 Programming Tutorial - Sockets Binding and listening, Python 3 Programming Tutorial - Sockets: client server system   https://www.youtube.com/watch?v=Q1a12QFq3os&list=PLQVvvaa0QuDe8XSftW-RAxdo6OmaeL85M&index=58

命令: telnet localhost 5555, 如果出现错误'telnet' is not recognized as an internal or external command, 解决方法:
Control Panel > Programs > Turn Windows features on or off 勾选 Telnet Client.

import socket
import sys
from _thread import *
host=''
port=5555
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
try:
    s.bind((host,port))
except socket.error as e:
        print(str(e))
s.listen(5)        

def threaded_client(conn):
    conn.send(str.encode('Welcome, type your info\n'))
    while True:
        data=conn.recv(2048)
        reply='Server output: '+data.decode('utf-8')
        if not data:
            break
        conn.sendall(str.encode(reply))    
    conn.close()

while True:
    conn,addr=s.accept()
    print('connected to: '+addr[0]+':'+str(addr[1]))
    start_new_thread(threaded_client,(conn,))

Python 2to3 - Convert your Python 2 to Python 3 automatically!    https://www.youtube.com/watch?v=8qxKYnAsNuU&index=60&list=PLQVvvaa0QuDe8XSftW-RAxdo6OmaeL85M
cmd窗口输入命令: C:\Users\H\Desktop\2to3me>python C:/Python34/Tools/scripts/2to3.py -w python2ugliness.py 

Python Pickle Module for saving objects (serialization)   https://www.youtube.com/watch?v=2Tw39kZIbhs&list=PLQVvvaa0QuDe8XSftW-RAxdo6OmaeL85M&index=61
import pickle
example_dict = {1:"6",2:"2",3:"f"}
#序列化
pickle_out = open("dict.pickle","wb")  #wb means write byte
pickle.dump(example_dict, pickle_out)
pickle_out.close()

#反序列化
pickle_in = open("dict.pickle","rb")  #rb means read byte
example_dict = pickle.load(pickle_in)
print(example_dict)
print(example_dict[2])
  
Python Eval programming tutorial      https://www.youtube.com/watch?v=1NJpqi5pqoU&index=62&list=PLQVvvaa0QuDe8XSftW-RAxdo6OmaeL85M
list_str = "[5,6,7,8,9]"
list_str = eval(list_str)
print(list_str)
print(list_str[2])

x = input("code: ")
check_this_out = eval(input("code"))
print(check_this_out)

Exec - Python programming tutorial    https://www.youtube.com/watch?v=ILPtmMAv7RM&list=PLQVvvaa0QuDe8XSftW-RAxdo6OmaeL85M&index=63
exec("print('so this works like eval')")

list_str = "[5,6,7,8,6]"
list_str = exec(list_str)
print(list_str2)

exec("def test(): print('o sniiii snap!!!')")
test()

exec("""
def test2():
    print('lets see if multi line works...')
""")
test2()

Creating a database, table, and inserting - SQLite3 with Python 3 part 1      https://www.youtube.com/watch?v=o-vsdfCBpsU&index=64&list=PLQVvvaa0QuDe8XSftW-RAxdo6OmaeL85M
import sqlite3
import time
import datetime
import random
import matplotlib.pyplot as plt  #打开https://pythonprogramming.net搜索matplotlib
import matplotlib.dates as mdates
from matplotlib import style
style.use('fivethirtyeight')

conn = sqlite3.connect('tutorial.db')
c = conn.cursor()
def create_table():
    c.execute('create table if not exists stuffToPlot(unix REAL, datestamp TEXT, keyword TEXT, value REAL)')
    
def data_entry():
    c.execute("insert into stuffToPlot values(123213,'2016-01-01','Python',5)")
    conn.commit()
    c.close()
    conn.close()
    
def dynamic_data_entry():
    unix = time.time()
    date = str(datetime.datetime.fromtimestamp(unix).strftime('%Y-%m-%d %H:%M:%S'))
    keyword = 'Python'
    value = random.randrange(0,10)
    c.execute("insert into stuffToPlot(unix,datestamp,keyword,value) values(?,?,?,?)",(unix,date,keyword,value))
    conn.commit()
    
def read_from_db():
    c.execute('select * from stuffToPlot')
    #data = c.fetchall()
    #print(data)
    for row in c.fetchall():
        print(row)
        
def graph_data():    
        c.execute('select unix, value from stuffToPlot')
        dates = []
        values = []
        from row in c.fetchall():
            dates.append(datetime.datetime.fromtimestamp(row[0]))
            values.append(row[1])
        plt.plot_date(dates,values,'-')
        plt.show()
        
def del_and_update():
            c.execute('select * from stuffToPlot')
            [print(row) for row in c.fetchall()]
            
            c.execute('update stuffToPlot set value=99 where value = 8')  #修改
            conn.commit()
            
            c.execute('delete from stuffToPlot where value = 99')  #删除
            conn.commit()
            print(50*'#')
    
#create_table()
#data_entry()
#for i in range(10):
#    dynamic_data_entry()
#    time.sleep(1)
#read_from_db()
#graph_data()
del_and_update()

c.close()
conn.close()
-----------------------------------------------------------------------------------------------------------------------------------------

 

posted on 2018-04-16 10:48  cw_volcano  阅读(425)  评论(0编辑  收藏  举报