python三大神器_常用Python代码及花式写法(函数调用自身+三大神器)
备注:第33课已经OK
一、urllib
from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup
my_url = "https://www.newegg.com/Video-Cards-Video-Devices/Category/ID-38?Tpk=graphic%20card"
# opening up connection, grabbing the page
uClient = uReq(my_url)
page_html = uClient.read()
uClient.close()
page_soup = soup(page_html,"html.parser")
print(page_soup.h1)
二、异常处理
使用下面的方法打印出错信息:
a = "yes"
for i in range(1,4):
try:
x = a+1
except Exception as e:
print(e)
# print("error message")
try的工作原理是,当开始一个try语句后,python就在当前程序的上下文中作标记,这样当异常出现时就可以回到这里,try子句先执行,接下来会发生什么依赖于执行时是否出现异常。
如果当try后的语句执行时发生异常,python就跳回到try并执行第一个匹配该异常的except子句,异常处理完毕,控制流就通过整个try语句(除非在处理异常时又引发新的异常)。
如果在try后的语句里发生了异常,却没有匹配的except子句,异常将被递交到上层的try,或者到程序的最上层(这样将结束程序,并打印缺省的出错信息)。
如果在try子句执行时没有发生异常,python将执行else语句后的语句(如果有else的话),然后控制流通过整个try语句。
三、读取CSV文件到SQlite
import pandas
import csv, sqlite3
conn= sqlite3.connect("dbname.db")
df = pandas.read_csv('btc2017_new2.csv')
df.to_sql('tablename', conn, if_exists='append', index=False)
print('ok')
四、读取txt
try:
f = open("guessword.txt")
words = f.read().splitlines()
f.close
excetp IOError:
print("Cannot find the 'gusssword.txt'")
exit()
五、读取文件夹下面的文件(使用glob)
filesIndex = 1
files = glob.glob("*.nille")
for filename in files:
print(str(filesIndex) + "."+ filename)
filesIndex = filesIndex + 1
六、函数内部调用自己
import threading
import time
def fun_timer():
print('hello timer')
global timer
#重复构造定时器
timer = threading.Timer(5.8,fun_timer)
timer.start()
#定时调度
timer = threading.Timer(2,fun_timer)
timer.start()
# 50秒后停止定时器
time.sleep(50)
timer.cancel()
另一个:
from threading import Timer
def hello():
print ("hello, world")
Timer(2.0, hello) .start()
t = Timer(2.0, hello)
t.start()
另一个:定时器:
threading中定时器Timer
定时器功能:在设置的多少时间后执行任务,不影响当前任务的执行。
import threading
from datetime import datetime
def fun_timer():
print("hello timer!===处理每秒触发的计时器事件:%s"% str(datetime.now()))
# 定义全局变量
global timer #timer可以改为其它名称
# 10秒调用函数一次
timer = threading.Timer(2, fun_timer)
# 启用定时器
timer.start()
fun_timer()
执行结果:
七、导入相同目录下的其他python文件
from .chan import *
命令式编程关键字: def if else for
函数式编程:关键字 map reduce filter三个函数,lambda算子
八、列表中的数值求和
from functools import reduce
list_x = [1,2,3,4,5,6,7,8]
r = reduce(lambda x,y:x+y,list_x)
print(r)
结果为36
九、filter
from functools import reduce
list_x = [1,0,1,0,5,0,7,8]
r = filter(lambda x: True if x ==1 else False,list_x)
print(list(r))
结果为[1, 1]
可以简写为:r = filter(lambda x: x,list_x)
十、装饰器
import time
def f1():
print(time.time())
print("This is a function")
f1()
如果要给上面一百个函数添加时间的功能呢?
import time
def f1():
# print(time.time())
print("This is a function")
# f1()
def print_current_time(func):
print(time.time())
func()
print_current_time(f1)
要懂装饰器首先要懂闭包,最好的视频还是这个:https://www.bilibili.com/video/BV1k7411i7oy?p=242
十一、叠代器
class MyNumbers:
def __iter__(self):
self.a = 1
return self
def __next__(self):
x = self.a
self.a += 1
return x
myclass = MyNumbers()
myiter = iter(myclass)
print(next(myiter))
print(next(myiter))
之前没懂,看完下面这个例子终于懂了:
class Fib():
"""什么样的对象对能被iterater?只要将下面两个方法定义好就可以了,就可以被for循化"""
def __init__(self):
self.a,self.b = 0, 1
def __iter__(self):
return self
def __next__(self):
self.a, self.b = self.b, self.a + self.b
return self.a
fib = Fib()
for i in fib:
if i>100:
break
print(i)
十二、生成器
import sys
def fibonacci(n): # 生成器函数 - 斐波那契
a, b, counter = 0, 1, 0
while True:
if (counter > n):
return
yield a
a, b = b, a + b
counter += 1
f = fibonacci(10) # f 是一个迭代器,由生成器返回生成
while True:
try:
print (next(f), end=" ")
except StopIteration:
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”的形式
=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] 表示脚本名
import sys
print '参数个数为:', len(sys.argv), '个参数。'
print '参数列表:', str(sys.argv)
输出结果为:
$ python test.py arg1 arg2 arg3
参数个数为: 4 个参数。
参数列表: ['test.py', 'arg1', 'arg2', 'arg3']
python三大神器_常用Python代码及花式写法(函数调用自身+三大神器)相关推荐
- python数据转换函数_常用python数据类型转换函数总结
1.chr(i) chr()函数返回ASCII码对应的字符串. >>> print chr(65) A >>> print chr(66) >>> ...
- python处理字符_常用python字符串处理
import re p = re.compile(r'\d+') print p.split('one1two2three3four4') ### output ### # ['one', 'two' ...
- python 时间序列预测_使用Python进行动手时间序列预测
python 时间序列预测 Time series analysis is the endeavor of extracting meaningful summary and statistical ...
- python 概率分布模型_使用python的概率模型进行公司估值
python 概率分布模型 Note from Towards Data Science's editors: While we allow independent authors to publis ...
- python hack库_常用的Python库
Tkinter---- Python默认的图形界面接口. Tkinter是一个和Tk接口的Python模块,Tkinter库提供了对Tk API的接口,它属于Tcl/Tk的GUI工具组.Tcl/Tk是 ...
- python编码尺寸_基于Python批量生成指定尺寸缩略图代码实例
这篇文章主要介绍了基于Python批量生成指定尺寸缩略图代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 最近我们商城上架的应用越来越丰富了. ...
- 用python实现点阵屏_用Python代码来绘制彭罗斯点阵的教程
这里是显示彭罗斯点阵的Python的脚本.是的,这是可以运行的有效Phython代码. 译注:彭罗斯点阵,物理学术语.上世纪70年代英国数学家彭罗斯第一次提出了这个概念,称为彭罗斯点阵(Pen-ros ...
- python网页版_经典python学习教程:20行代码打造一个微信群聊助手,解放双手
今天的Python学习教程教大家如何用20行Python代码实现微信群聊助手,可以用来活跃群气氛,好多群主创建完群后,拉完一群人,之后就一片寂静,有个群聊助手,就可以帮忙活跃群里气氛,通过今天在自己的 ...
- python编程的常用工具_小白学Python(2)——常用Python编程工具,Python IDE
下载好Python,但是如何开始编程呢? 有几种方法, 1.第一个就是command lind 即为命令行的方式,也就是我们常说的cmd. 输入 win+ cmd 在命令行中再输入 python,即可 ...
最新文章
- 蓝绿部署、金丝雀发布(灰度发布)、AB测试……
- 光敏电阻与光强之间什么关系?
- 用作键提取器的函数的 Boost.MultiIndex 示例
- 使用谷歌浏览器模拟微信(android或ios)浏览器
- Report not added to business roles
- Js正则表达式数字或者带小数点的数字
- 吴恩达机器学习训练2:Logistic回归
- BUG类算法研究分析
- java可以实现agv调度吗_AGV路线优化及实时调度
- Python 基础 —— Python程序员常犯的那些错误
- 第三次作业代码规范修改
- BFS算法解题套路框架(附习题)
- 华为的计算机怎么没声音怎么办,笔记本电脑没有声音怎么办
- Alt属性和Title属性
- 【Add_two_numbers】
- Core Animation学习笔记—第二节Setting up Layer Objects
- JS复制文本到粘贴板,前端H5移动端点击按钮复制文本到粘贴板。
- 用累积分布函数(CDF)计算期望
- SSM+人才交流平台 毕业设计-附源码221022
- mysql中的dual