Home >  > 常用Python代码及花式写法(函数调用自身+三大神器)

常用Python代码及花式写法(函数调用自身+三大神器)

0

备注:第33课已经OK

一、urllib

1from urllib.request import urlopen as  uReq
2from bs4 import BeautifulSoup as soup
3 
5# opening up connection, grabbing the page
6uClient = uReq(my_url)
7page_html = uClient.read()
8uClient.close()
9page_soup = soup(page_html,"html.parser")
10print(page_soup.h1)

二、异常处理
使用下面的方法打印出错信息:

1a  = "yes"
2for i in range(1,4):
3    try:
4        x = a+1
5    except Exception as e:
6        print(e)
7        # print("error message")

try的工作原理是,当开始一个try语句后,python就在当前程序的上下文中作标记,这样当异常出现时就可以回到这里,try子句先执行,接下来会发生什么依赖于执行时是否出现异常。

如果当try后的语句执行时发生异常,python就跳回到try并执行第一个匹配该异常的except子句,异常处理完毕,控制流就通过整个try语句(除非在处理异常时又引发新的异常)。

如果在try后的语句里发生了异常,却没有匹配的except子句,异常将被递交到上层的try,或者到程序的最上层(这样将结束程序,并打印缺省的出错信息)。

如果在try子句执行时没有发生异常,python将执行else语句后的语句(如果有else的话),然后控制流通过整个try语句。

三、读取CSV文件到SQlite

1import pandas
2import csv, sqlite3
3conn= sqlite3.connect("dbname.db")
4df = pandas.read_csv('btc2017_new2.csv')
5df.to_sql('tablename', conn, if_exists='append', index=False)
6print('ok')

四、读取txt

1try:
2    f = open("guessword.txt")
3    words = f.read().splitlines()
4    f.close
5excetp IOError:
6    print("Cannot find the 'gusssword.txt'")
7    exit()

五、读取文件夹下面的文件(使用glob)

1filesIndex = 1
2files = glob.glob("*.nille")
3for filename in files:
4    print(str(filesIndex) + "."+ filename)
5    filesIndex = filesIndex + 1

六、函数内部调用自己

1import threading
2import time
3 
4def fun_timer():
5    print('hello timer')
6    global timer
7    #重复构造定时器
8    timer = threading.Timer(5.8,fun_timer)
9    timer.start()
10#定时调度
11timer = threading.Timer(2,fun_timer)
12timer.start()
13 
14 
15# 50秒后停止定时器
16time.sleep(50)
17timer.cancel()

另一个:

1from threading import Timer
2def hello():
3    print ("hello, world")
4    Timer(2.0, hello) .start()
5 
6t = Timer(2.0, hello)
7t.start()

另一个:定时器:
threading中定时器Timer
定时器功能:在设置的多少时间后执行任务,不影响当前任务的执行。

1import threading
2from datetime import datetime
3  
4  
5def fun_timer():
6    print("hello timer!===处理每秒触发的计时器事件:%s"% str(datetime.now()))
7    # 定义全局变量
8    global timer  #timer可以改为其它名称
9    # 10秒调用函数一次
10    timer = threading.Timer(2, fun_timer)
11    # 启用定时器
12    timer.start()
13  
14  
15fun_timer()

执行结果:

七、导入相同目录下的其他python文件

1from .chan import *

命令式编程关键字: def if else for

函数式编程:关键字 map reduce filter三个函数,lambda算子

八、列表中的数值求和

1from functools import reduce
2 
3list_x = [1,2,3,4,5,6,7,8]
4 
5r = reduce(lambda x,y:x+y,list_x)
6 
7print(r)

结果为36

九、filter

1from functools import reduce
2 
3list_x = [1,0,1,0,5,0,7,8]
4 
5r = filter(lambda x: True if x ==1 else False,list_x)
6print(list(r))

结果为[1, 1]

可以简写为:r = filter(lambda x: x,list_x)

十、装饰器

1import time
2 
3def f1():
4    print(time.time())
5    print("This is a function")
6 
7f1()

如果要给上面一百个函数添加时间的功能呢?

1import time
2 
3def f1():
4    # print(time.time())
5    print("This is a function")
6 
7# f1()
8 
9 
10def print_current_time(func):
11    print(time.time())
12    func()
13 
14 
15print_current_time(f1)

要懂装饰器首先要懂闭包,最好的视频还是这个:https://www.bilibili.com/video/BV1k7411i7oy?p=242

十一、叠代器

叠代器的优点就是占用很小的空间,它存储的不是数据,而是产生数据的方法。

https://www.bilibili.com/video/BV1Fb411L7d8/?spm_id_from=autoNext

1class MyNumbers:
2  def __iter__(self):
3    self.a = 1
4    return self
5  
6  def __next__(self):
7    x = self.a
8    self.a += 1
9    return x
10  
11myclass = MyNumbers()
12myiter = iter(myclass)
13print(next(myiter))
14print(next(myiter))

之前没懂,看完下面这个例子终于懂了:

1class Fib():
2    """什么样的对象对能被iterater?只要将下面两个方法定义好就可以了,就可以被for循化"""
3    def __init__(self):
4        self.a,self.b = 0, 1
5 
6    def __iter__(self):
7        return self
8 
9    def __next__(self):
10        self.a, self.b = self.b, self.a + self.b
11        return self.a
12 
13 
14fib = Fib()
15for i in fib:
16    if i>100:
17        break
18    print(i)
19        

这个视频解释得很好:https://www.bilibili.com/video/av50369911/

十二、生成器
是一种特殊的迭代器。
将推导列表的方括号变成圆括号,就是生成器。用yield。
g= (x** for x in range(10))

1import sys
2  
3def fibonacci(n): # 生成器函数 - 斐波那契
4    a, b, counter = 0, 1, 0
5    while True:
6        if (counter > n):
7            return
8        yield a
9        a, b = b, a + b
10        counter += 1
11f = fibonacci(10) # f 是一个迭代器,由生成器返回生成
12  
13while True:
14    try:
15        print (next(f), end=" ")
16    except StopIteration:
17        sys.exit()

结果:
“0 1 1 2 3 5 8 13 21 34 55”

十三、闭包
看了很多说明,还是没有说明白的,后来看了这个视频懂了:闭包就是外面的函数返回里面的函数的地址。
https://www.bilibili.com/video/BV1k7411i7oy?p=240

十三、其他
1.列表生成式
[stock for stock in tohold if stock not in context.portfolio.positions ]

十四、股票权重生成器

十五、处理时间格式
将“201902251030”的时间格式转化为“2010-02-25 10:30”的形式

1=df['candel_end_time'].apply(lambda x: '%s-%s-%s' %s:%s) % (x[0:4],x[4:6],x[6:8],x[8:10],x[10:12])

十六、sys.argv[0] 表示脚本名

1import sys
2 
3print '参数个数为:', len(sys.argv), '个参数。'
4print '参数列表:', str(sys.argv)

输出结果为:

1$ python test.py arg1 arg2 arg3
2参数个数为: 4 个参数。
3参数列表: ['test.py', 'arg1', 'arg2', 'arg3']

十七、 if写成一行,采集的时候,比如要写两个采集规则的时候可以使用。

1a = []
2 
3b = 5
4 
5c = a if a else b
6print(c)

执行结果为5。

暧昧帖

本文暂无标签

发表评论

*

*