一、函数
1、用户传入修改的文件名,指定要修改的内容,执行函数,完成批量修改的操作
1
2
3
4
5
6
7
8
9
10
|
def
modify_file(filename,old,new):
import
os
with
open
(filename,
'r'
,encoding
=
'utf-8'
) as read_f,
open
(
'.bak.swap'
,
'w'
,encoding
=
'utf-8'
) as write_f:
for
line
in
read_f:
if
old
in
line:
line
=
line.replace(old,new)
write_f.write(line)
#修改过的内容写到临时文件.bak.swap
os.remove(filename)
#将源文件删除
os.rename(
'.bak.swap'
,filename)
#将临时文件.bak.swap重命名为之前的文件名filename
modify_file(
'/Users/jieli/a.txt'
,
'some'
,
'same'
)
#用户传递参数,实现将a.txt中的some改为same
|
2、写函数,计算传入字符串中【数字】、【字母】、【空格] 以及 【其他】的个数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
def
check(msg):
res
=
{
'num'
:
0
,
'string'
:
0
,
'space'
:
0
,
'other'
:
0
,
}
for
s
in
msg:
if
s.isdigit():
#判断属于数字
res[
'num'
]
+
=
1
elif
s.isalpha():
#判断属于字符串
res[
'string'
]
+
=
1
elif
s.isspace():
#判断属于空格
res[
'space'
]
+
=
1
else
:
res[
'other'
]
+
=
1
return
res
res
=
check(
'hello name:jim passowrd:win2008'
)
#给函数传入参数‘hello name:jim passowrd:win2008’
print
(res)
#结果是{'num': 4, 'string': 23, 'space': 2, 'other': 2}
|
3、写函数,判断用户传入的对象(字符串、列表、元组)长度是否大于5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
def
func1(
str
,
list
,tup):
zi
=
len
(
str
)
li
=
len
(
list
)
tup
=
len
(tup)
if
zi >
5
:
print
(
"字符串长度大于5"
)
else
:
print
(
"字符串长度小于或等于5"
)
if
li >
5
:
print
(
"列表长度大于5"
)
else
:
print
(
"列表长度小于或等于5"
)
if
tup >
5
:
print
(
"元组长度大于5"
)
else
:
print
(
"元组长度小于或等于5"
)
func1(
"kwkwqehk"
,[
11
,
22
,
33
],(
1
,
"215"
,
5
,
6
,
59
,
6
))
|
4、写函数,检查传入列表的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者。
1
2
3
4
5
|
def
func1(seq):
if
len
(seq) >
2
:
seq
=
seq[
0
:
2
]
#根据索引取元素,索引为0和1的
return
seq
print
(func1([
1
,
2
,
3
,
4
]))
#结果是[1, 2]
|
5、写函数,检查获取传入列表或元组对象的所有奇数位索引对应的元素,并将其作为新列表返回给调用者
1
2
3
|
def
func2(seq):
return
seq[::
2
]
#按照索引判断,指定步长为2
print
(func2((
1
,
2
,
3
,
4
,
5
,
6
,
7
)))
#结果是(1, 3, 5, 7)
|
6、写函数,检查字典的每一个value的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者
1
2
3
4
5
6
7
|
def
func3(dic):
d
=
{}
for
key,value
in
dic.items():
if
len
(value) >
2
:
#value长度大于2的
d[key]
=
value[
0
:
2
]
#新的value保留两个长度的内容,并和key组成新字典d
return
d
print
(func3({
'k1'
:
'abcdef'
,
'k2'
:[
1
,
2
,
3
,
4
],
'k3'
:(
'a'
,
'b'
,
'c'
)}))
#结果是{'k1': 'ab', 'k2': [1, 2], 'k3': ('a', 'b')}
|
二、装饰器
1、写一个执行的时间是随机的函数
1
2
3
4
5
6
|
import
random
import
time
def
func1():
time.sleep(random.randrange(
1
,
5
))
#random的randrange生成随机的时间1到4秒
print
(
'welecome to func1'
)
func1()
|
2、编写装饰器,为函数加上统计时间的功能
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
import
time
import
random
from
functools
import
wraps
def
wrap(func):
def
auth(
*
args,
*
*
kwargs):
start
=
time.time()
res
=
func(
*
args,
*
*
kwargs)
stop
=
time.time()
print
(
'run time is %s'
%
(stop
-
start))
return
res
return
auth
@wrap
#装饰器语法,相当于执行wrap(func)
def
func():
time.sleep(random.randrange(
1
,
5
))
print
(
'welecome to func'
)
func()
|
3、编写装饰器,为函数加上认证的功能
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
import
time
def
wrap(func):
def
auth(
*
args,
*
*
kwargs):
while
True
:
name
=
input
(
'username: '
).strip()
password
=
input
(
'pwd: '
).strip()
if
name
=
=
'wang'
and
password
=
=
'123'
:
print
(
'successful'
)
res
=
func(
*
args,
*
*
kwargs)
return
res
else
:
print
(
'error'
)
continue
return
auth
@wrap
def
index():
print
(
'welecome to func1'
)
index()
|
4、编写装饰器,为多个函数加上认证的功能(用户的账号密码来源于文件),要求登录成功一次,后续的函数都无需再输入用户名和密码
db文件内容:{'alex':'123','wang':'123'}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
login_status
=
{
'user'
:
None
,
'status'
:
False
}
#用户输入一次,不管正确还是错误都结束程序
def
auth(auth_type
=
'file'
):
def
auth2(func):
def
wrapper(
*
args,
*
*
kwargs):
if
login_status[
'user'
]
and
login_status[
'status'
]:
return
func(
*
args,
*
*
kwargs)
if
auth_type
=
=
'file'
:
with
open
(r
'C:\Users\db'
,encoding
=
'utf-8'
) as f:
dic
=
eval
(f.read())
name
=
input
(
'username: '
).strip()
password
=
input
(
'password: '
).strip()
if
name
in
dic
and
password
=
=
dic[name]:
login_status[
'user'
]
=
name
login_status[
'status'
]
=
True
res
=
func(
*
args,
*
*
kwargs)
return
res
else
:
print
(
'username or password error'
)
elif
auth_type
=
=
'sql'
:
print
(
'from sql'
)
else
:
print
(
'error press'
)
return
wrapper
return
auth2
@auth
()
def
index():
print
(
'index'
)
@auth
(auth_type
=
'file'
)
def
home(name):
print
(
'welcome %s to home'
%
name)
index()
home(
'wang'
)
|
5、编写装饰器,为多个函数加上认证功能,要求登录成功一次,在超时时间内无需重复登录,超过了超时时间,则必须重新登录
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
import
time,random
user
=
{
'user'
:
None
,
'login_time'
:
None
,
'timeout'
:
3.000003
,}
def
timmer(func):
def
wrapper(
*
args,
*
*
kwargs):
s1
=
time.time()
res
=
func(
*
args,
*
*
kwargs)
s2
=
time.time()
print
(
'%s'
%
(s2
-
s1))
return
res
return
wrapper
def
auth(func):
def
wrapper(
*
args,
*
*
kwargs):
if
user[
'user'
]:
timeout
=
time.time()
-
user[
'login_time'
]
if
timeout < user[
'timeout'
]:
return
func(
*
args,
*
*
kwargs)
name
=
input
(
'name>>: '
).strip()
password
=
input
(
'password>>: '
).strip()
if
name
=
=
'egon'
and
password
=
=
'123'
:
user[
'user'
]
=
name
user[
'login_time'
]
=
time.time()
res
=
func(
*
args,
*
*
kwargs)
return
res
return
wrapper
@auth
def
index():
time.sleep(random.randrange(
3
))
print
(
'welcome to index'
)
@auth
def
home(name):
time.sleep(random.randrange(
3
))
print
(
'welcome %s to home '
%
name)
index()
home(
'wang'
)
|
6、编写日志装饰器,一旦函数f1执行,则将消息2017-07-21 11:12:11 f1 run写入到日志文件中
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
import
time
import
os
def
logger(logfile):
def
deco(func):
if
not
os.path.exists(logfile):
#日志文件不存在pass
with
open
(logfile,
'w'
):
pass
def
wrapper(
*
args,
*
*
kwargs):
res
=
func(
*
args,
*
*
kwargs)
with
open
(logfile,
'a'
,encoding
=
'utf-8'
) as f:
#文件里面追加时间标记
f.write(
'%s %s run\n'
%
(time.strftime(
'%Y-%m-%d %X'
),func.__name__))
return
res
return
wrapper
return
deco
@logger
(logfile
=
'aaa.log'
)
def
index():
print
(
'index'
)
index()
|
三、声明式编程练习
1、将names=['zhao','qian','sun','li']中的名字全部变大写
1
2
|
names
=
[name.upper()
for
name
in
names]
print
(names)
|
2、将names=['zhao','qian','sun','li']中以i结尾的过滤掉,保存剩下的名字长度
1
2
|
names
=
[name
for
name
in
names
if
not
name.endswith(
'sb'
)]
print
(names)
#结果['zhao', 'qian', 'sun']
|
3、求文件a.txt中最长的行的长度(长度按字符个数算,需要使用max函数)
1
2
3
|
with
open
(
'aaa.log'
,
'r'
,encoding
=
'utf-8'
) as f:
res
=
max
(
len
(line)
for
line
in
f)
print
(res)
|
4、文件shopping.txt内容如下
mac 20000 3
lenovo 3000 10
tesla 1000000 10
chicken 200 1
(1)开支是多少
1
2
3
4
5
|
with
open
(
'shopping.txt'
, encoding
=
'utf-8'
) as f:
info
=
[line.split()
for
line
in
f]
#print(info) #[['mac', '20000', '3'], ['lenovo', '3000', '10'], ['tesla', '1000000', '10'], ['chicken', '200', '1']]
cost
=
sum
(
float
(unit_price)
*
int
(count)
for
_, unit_price, count
in
info)
print
(cost)
#结果是支出的金额
|
(2)打印信息,如格式为[{'name':'xxx','price':333,'count':3},...]
1
2
3
4
5
6
7
|
with
open
(
'a.txt'
,encoding
=
'utf-8'
) as f:
info
=
[{
'name'
: line.split()[
0
],
#取第一列的名字
'price'
:
float
(line.split()[
1
]),
#取第二列的价钱 转化为float类型
'count'
:
int
(line.split()[
2
]),
#取第三列的个数 int类型
}
for
line
in
f]
print
(info)
|
(3)单价大于10000的商品信息
1
2
3
4
5
6
7
|
with
open
(
'a.txt'
,encoding
=
'utf-8'
) as f:
info
=
[{
'name'
: line.split()[
0
],
'price'
:
float
(line.split()[
1
]),
'count'
:
int
(line.split()[
2
]),
}
for
line
in
f
if
float
(line.split()[
1
])>
10000
]
print
(info)
|
本文转自 宋鹏超 51CTO博客,原文链接:http://blog.51cto.com/qidian510/2057802,如需转载请自行联系原作者