Python review
Meditly ComputerSavvyMedic
It has been 0 days since the last update of this post. Some contents may be outdated. Please pay attention to screening.

Python 相关复习资料,包括网络平台题库、期末复习、基本函数、题库、基本方法和常用函数等。

python期末复习

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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
#变量开头不能为数字

##print(3/1)#3.0

##16)表达式 min({3:7,10:5,1:6})的结果是( B) 。
##A、6
##B、1
##C、5
##D、{1:6}
#字典中使用min函数比大小,比的是键

##17)以下语句执行结果是( C) 。
##s = 'HelloWorld'
##print(s[5::-2])
##A、drW
##B、olH
##C、Wle
##D、loo

#起点,终点,步频,“”不包括在内

##3.替换方法str.replace(old,new[,count])#可以不要count
##s = "I have a dream"
##print(s.replace(" ",","))#I,have,a,dream
##print(s.replace(" ",",",2))#I,have,a dream

##4.lstrip(),rstrip(),strip(),分别去除字符串左边,右边
##左右两边的空格或指定符号
##s=" python "
##print(s)
##print(s.strip())

##import string
##s="a"
##print(s in string.printable)

##random.random() 返回[0,1)之间的随机浮点数N
##import random
##print(random.random())

##22)以下代码的输出结果是(D)。
##ls = "ab"
##print("{{}}{:+^4}".format(ls))
##A、+ab+{}
##B、{{}}+ab+
##C、+ab+{}
##D、{}+ab+
#注意:'{{'表示{
# '}}'表示}
##print("{{{:+^4}}}".format(ls))
#{+ab+}
##print("{{:+^4}}".format(ls))#{:+^4}
#print("{}{:+^4}".format("ab"))#{}+ab+

##x=50
##print("函数外部打印 x 的值:",x)
##def func(n):
## global x
## x+=n
## print("函数内部打印 x 的值:",x)
##func(20)
##函数外部打印 x 的值: 50
##函数内部打印 x 的值: 70

##def func(n):
## global x
## x+=n
## print("函数内部打印 x 的值:",x)
##
##x=50
##func(20)
##print("函数外部打印 x 的值:",x)
##函数内部打印 x 的值: 70
##函数外部打印 x 的值: 70

##def func(n):
## x=10
## x+=n
## print("函数内部打印 x 的值:",x)
##
##x=50
##func(20)
##print("函数外部打印 x 的值:",x)
##函数内部打印 x 的值: 30
##函数外部打印 x 的值: 50

##def jesus():
## print("you are the best")
##a=jesus()
##print(a)
##you are the best
##None

##25)关于 Python 函数的描述错误的是(A) 。
##A、函数内部使用的全局变量必须用 global 声明
##B、Python 支持可选参数传递,但没有默认值的参数必须定义在有默认值参数的左侧
##C、Python 函数可以没有 return 语句,此时返回值为 None
##D、Python 函数支持用名称传递参数

#仅调用全局变量的时候不需要声明,如若要对其进行修改,则需要声明global

##26)以下程序的输出结果是(D)。
##def func(x =[], y =[6,7]):
## x.append(8)
## y.append(8)
## return(x+y)
##a, b = [1,2], [3,4]
##t=func(x=a)
##t=func(y=b)
##print(func() ,end=";")
##A、[8,8,6,7,8,8]
##B、[8,6,7,8,8];
##C、[8,6,7,8,8]
##D、[8,8,6,7,8,8];
##第一次调用 [1,2,8]#[6,7,8](y的新默认值)
## [1,2,8,6,7,8]
##第二次调用 #[8](x的新默认值)[3,4,8]
## [8,3,4,8]
##第三次调用 [8][6,7,8]
## [8,8,6,7,8,8]
##第一次调用时改了形参y的默认值列表,默认值变成[6,7,8]
##第二次调用时改了形参x的默认值列表,默认值变成[8]
##默认值列表被改变了,关键点就在这里
##后两次调用没有传递实参,都用的改变了的默认参数值

##斐波那契数列
#非递归
#方法一:多变量迭代
##def Fib(n):
## f0=1
## f1=1
## for i in range(2,n+1):
## f2=f1+f0
## f0=f1
## f1=f2
## return f2
##a=eval(input("请输入数字:"))
##print(Fib(a))

#方法二:利用列表
##def Fib(n):
## Fiblist=[1,1]
## for i in range(2,n+1):
## Fiblist+=[Fiblist[-1]+Fiblist[-2]]
## return Fiblist[n]
##a=eval(input("请输入数字:"))
##print(Fib(a))

#递归
##def Fib(n):
## if n==0 or n==1:
## return 1
## else:
## return Fib(n-1)+Fib(n-2)
##a=eval(input("请输入数字:"))
##print(Fib(a))

##ls = ["ab","44","cd","46"]
##ls.reverse()

##print(ls)
##print("".join(ls))
##'sep'.join(seq)
##以sep作为分隔符,将seq所有的元素合并成一个新的字符串

##ss =[2,3,6,9,7,1]
##for i in ss:
## ss.remove(min(ss))
## print(min(ss),end = ",")

##[2,3,6,9,7]2(0)
##[3,6,9,7]3(1)
##[6,9,7]6(2)

##dd = {'a':90,'b':87,'c':93}
##print([[dd[x], x] for x in sorted(dd)])
##dd = {'chinese':200,'pe':187,'Gana':930}
##print(sorted(dd.keys()))#['Gana', 'chinese', 'pe']
##输出为列表

##可选参数,是指给方法的特定参数指定默认值,在调用方法时可以省略掉这些参数
##(1)可选参数不能为参数列表的第1个参数,必须位于所有的必选参数之后
##(除非没有必选参数);
##(2)可选参数必须指定一个默认值,且默认值必须是一个常量表达式,不能为变量;
##(3)所有可选参数以后的参数都必须是可选参数。

##print(ord("a"))
##print(int(-3.5))

#n的阶乘
##n=int(input("n="))
##fact=1
##for i in range(2,n+1):
## fact*=i
##print(n,"!=",fact)

#s的逆序
##s=input("s=")
##t=""
##for i in s:
## t=i+t
##print(t)

#最大公约数
##n=int(input("n:"))
##m=int(input("m:"))
##r=n%m
##while r!=0:
## n=m
## m=r
## r=n%m
##print(m)

#找出三位数中每一位数字都是素数的数
##for i in range(100,1000):
## st=str(i)
## flag=True
## for j in st:
## if int(j)<2:
## flag=False
## break
## else:
## for k in range(2,int(j)):
## if int(j)%k==0:
## flag=False
## break
## if flag==False:
## break
## if flag==True:
## print(i)

##img1 = [12,34,56,78]
##print(id(img1))#2222227057536
##img2 = [1,2,3,4,5]
##print(id(img2))#2222258359936
##def modi():
## img1 =img2
## print(id(img1))#2222258359936
## print(img1)
##modi()
##print(id(img1))#2222227057536
##print(img1)
#区别形参实参传递时的列表

##print(ord("b"))#98

#判断完数(该数字恰好等于它的因子之和)
##def ws(n):
## sum=0
## for i in range(1,n):
## if n%i==0:
## sum+=i
## if sum==n:
## return True
##a=eval(input("n="))
##if ws(a):
## print("是")
##else:
## print("不是")

#最小公倍数
##def lcd(m,n):
## r=m%n
## a=m*n
## while r!=0:
## m=n
## n=r
## r==m%n
## return a//n
##m=eval(input("m="))
##n=eval(input("n="))
##print("是",a//n)

#判断回文数
##def judge(n):
## s=str(n)
## t=""
## for i in s:
## t=i+t
## if t==s:
## return True
## else:
## return False
##a=eval(input("n="))
##if judge(a):
## print("是")
##else:
## print("不是")

#判断降序数
##def jx(n):
## s=str(n)
## for i in range(len(s)-1):
## if s[i]<=s[i+1]:
## return False
## return True
##a=eval(input("n="))
##if jx(a):
## print("√")
##else:
## print("×")

#随机生成5个[1,50]之间的随机整数
##import random
##for i in range(5):
## print(random.randint(1,50))

#类凯撒密码
##s=eval(input("请输入:"))
##t=[]
##for i in range(65,91):
## t.append(chr(i))
##print("输出对应大写字母:{}".format(t[s-1]))

#数字的进制转化
##n=eval(input("请输入:"))
##print("对应的二进制数:{0:b}\n八进制数:{0:o}\n十六进制数:{0:X}".format(n))

#阶乘和
##import random
##def fact(n):
## if n==0 or n==1:
## return 1
## s=1
## for i in range(1,n+1):
## s*=i
## return s
##lis=[]
##cnt=0
##while cnt<10:
## x=random.randint(100,999)
## lis+=[x]
## cnt+=1
##for i in lis:
## sum1=0
## st=""
## t=str(i)
## for j in t:
## sum1+=fact(int(j))
## st+=j+"!+"
## print(i,":",st[:-1],"=",sum1)

#升序数
##import random
##def ascnum(n):
## st=str(n)
## for i in range(len(st)-1):
## if st[i]>=st[i+1]:
## return False
## return True
##
##lis=[]
##cnt=0
##while cnt<20:
## x=random.randint(100,999)
## if x not in lis:
## lis+=[x]
## cnt+=1
##print(lis)
##cnt=0
##for n in lis:
## if ascnum(n):
## cnt+=1
## print(n,end="")
##if cnt==0:
## print("无升序数")

#仅由1,2,3组成的1,2,3位素数
##def prime(n):
## if n<2:
## return False
## for i in range(2,n):
## if n%i==0:
## return False
## return True
##
##s="123"
##for i in range(1,334):
## flag=True
## n=str(i)
## for j in n:
## if j not in s:
## flag=False
## break
## if flag==True:
## if prime(i):
## print(i)

##import jieba
##txt=input("请输入:")
##ls=jieba.lcut(txt)
##for i in ls[::-1]:
## print(i,end="")

##import string
##fi=open("小女孩.txt","r")
##fo=open("词频统计.txt","w")
##txt=fi.read()
##fi.close()
##d={}
##exclude=string.punctuation+string.whitespace
##for word in txt:
## if word not in exclude:
## d[word]=d.get(word,0)+1
## ls=list(d.items())
## ls.sort(key=lambda item:item[1],reverse=True)
## for i in range(len(ls)):
## ls[i]="{}:{}".format(ls[i][0],ls[i][1])
## fo.write(",".join(ls))
##fo.close()

##fi=open("vacation.csv","r")
##ls=[]
##for line in fi:
## ls.append(line.strip("\n").split(","))
##fi.close()
##s=input("请输入节假日序号:")
##while s!="":
## slist=[s,split]
## for i in slist:
## flag=False
## for line in ls:
## if flag=True:
## print("{}")

#三国演义分词
##import jieba
##f=open("data.txt","r")
##lins=f.readlines()
##f.close()
##f=open("out.txt","w")
##wordlist=[]
##for line in lines:
## line=line.strip()
## wordlist+=jieba.lcut(line)
##f.write("\n".join(wordlist))

##f=open("name.txt")
##names=f.readlines()
##f.close()
##f=open("vote.txt")
##votes=f.readlines()
##print(votes)
##f.close()
##f=open("vote1.txt","w")
##d={}
##NUM=0
##for vote in votes:
## print(vote)
## num=len(vote.split())
## if num==1 and vote in names:
## d[vote[:-1]]=d.get(d[vote[:-1]],0)+1
## NUM+=1
## else:
## f.write(vote)
##f.close()
##ls=list(d.items())
##ls.sort(key=lambda s:s[1],reverse=True)
##name=ls[0][0]
##score=ls[0][1]
##print("有效选票{}当选村长的村民{}票数{}".format(NUM,name,score))

##2
##[1,1,2]
##3
##[1,1,2,3]
##4
##[1,1,2,3,5]

##print (2>2>5)
##abcdefghijklmnopqrstuvwxyz

##def proc(strings):
## m=0
## lst=[]
## for i in range(len(strings)):
## if len(strings[i])>m:
## m=len(strings[i])
## for i in range(len(strings)):
## if len(strings[i])==m:
## lst.append(strings[i])
## return lst
##strings=["cad","VB","Python","MATLAB","hello","world"]
##result=proc(strings)
##print("the longest words are:")
##for item in result:
## print("{:>25}".format(item))

##import jieba
##txt=input("请输入一段中文文本:")
##ls=jieba.lcut(txt)
##print(ls)
##print("{:.1f}".format(len(txt)/len(ls)))

##n=input("请输入电话号码:")
##s="〇一二三四五六七八九"
##for c in "0123456789":
## n=n.replace(c,s[int(c)])
##print(n)

##str.replace(old,new[,max])

python基本函数

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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
####一、基本数字类型及运算符
####三类数字类型:
####1.整数型 int
##a=123
##print(a,type(a))
####2. 浮点数型 float:两种表示方法:十进制和科学计数法
##a=2.0
##print(a,type(a))
##b=3.145E-9
##print(b,type(b))
####3. 复数型 complex
##a=2+3j
##print(a,type(a))
#### 布尔型 bool:True 和 False
##print(2+True)
##print(2+False)
##a=True
##print(a,type(a))
##print(int(True))
##print(int(False))
##print(bool(-2.3))
##print(bool(0))
####数字运算
####1.算术运算符(+,-,*,/,//,%,**)
####x/y 浮点除,结果为浮点数
####x//y 地板除,结果为整数
##print(5/-2)
##print(5//-2.0)
####算术运算符的优先级 **→(+ -)→* / // % → + -
##print(30//7*4+15%-2**4)
##print(30//7*4+15%(-2)**4)
##赋值运算符
##x=2.0
##print(x)
##x=1
##print(x)
##x=x+1
####print(x)
####x+=1
##print(x)
##x*=3+5**2
##print(x)
##a,b=1,2
##print(a,b)
##a,b=b,a
##print(a,b)
####2. 比较运算符(>,>=,<,<=,!=,==)
##print(3==5)
##print('asd'>='asde')
####3. 逻辑运算符(and,or,not)
##print(10 and True)
##print(10 or True)
##print(10 and 12)
##print(10 or 12)
####4.位运算符(&,|,^,~,<<,>>)
####常用函数
##print(int(3.8))
##print(float(33))
##n=input('n:')
##print(eval(n)+4)
##print(abs(-8.9))
##a,b=divmod(17,5)
##print(a)
##print(b)
##n=divmod(17,5)
##print(n)
##print(pow(9,0.5))
##print(round(3124.135,-2))
##print(bin(15))
##print(oct(15))
##print(hex(15))
####标准库
####math: 数 学 函 数 (floor 取 整 largest integer<=x,ceil 取 整 smallest
integer>=x,sqrt,pi,sin,e,log...)
####random:随机数生成器(randint,uniform,random)
##import math
##print(math.floor(-3.6))
##print(math.floor(3.6))
##print(math.ceil(-3.6))
##print(math.ceil(3.6))
##print(math.pi)
##print(math.sin(math.pi/2))
##print(math.e)
##print(math.log(math.e))
##print(math.sqrt(4))
##from random import *
##print(randint(10,20))
##print(random())
##print(uniform(10,20))
####二 、序列(列表、字符串、元组)
##序列的通用操作(连接+、重复*、成员判断 in、切片[][:][::])
##(一)、列表
##1、创建列表
##a=[1,2,3]
##b=list('abcd')
##print(a)
##print(b)
##2、添加列表元素
##list1 = [5, 1, 8]
##list1.append(10)
##print(list1)
##若在指定位置插入元素用 intert()方法:
##intert(插入位置,插入元素)
##list1.insert(2,6)
##print(list1)
##3、获取列表元素
##可以通过切片方式获取,只需要给定元素的位置(索引)
##list2=['a','b','c','d']
##print(list2[1])
##使用 for 循环输出列表元素
##lis=[1,2,3,4,5,6]
##for i in lis:
## print(i,end=" ")
##4、删除列表元素
##remove()方法、pop()方法和 del
##lis=[3,1,2,3,4,5,6]
##lis.remove(3)
##print(lis)
##remove 方法只需要知道要删除的元素在列表中,不需要知道元素的位置。
##若删除的元素不在列表中,则报错。如果多个重复值存在,remove 方法只删除第一个指
定的值,
##pop()方法删除列表末尾的元素,如果使用参数指定位置,则可以删除任意位置上的元素。
##lis=[1,2,3,4,5,6]
##lis.pop()
##print(lis)
##lis.pop(1)
##print(lis)
##del 加上列表名,可以删除整个列表
##del lis
##del 加上列表名[索引]可以删除任意位置的元素
##lis=[1,2,3,4,5,6]
##del lis[3]
##print(lis)
##5、列表的其它常用方法
##(1)count()
##返回元素出现的次数
##lis=[1,2,3,2,4,5,2,6,3]
##print(lis.count(2))
##(2)extend()
##在列表末尾一次性追加另一个序列的所有元素
##lis1=[1,2,3,4,5,6]
##lis2=[4,8,9,15]
##lis1.extend(lis2)
##print(lis1)
##(3)index
##index(x)方法返回列表中出现的 x 元素的索引序号、若不存在该元索则报错。
##lis=[1,2,1,2,5,4,8,2]
##print(lis.index(2))
##print(lis.index(2,4))
##print(lis.index(3))
##(4)reverse()
##反转列表元素的排列顺序
##num=[1,2,3,4,5]
##num.reverse()
##print(num)
##(5)sort()、sorted()
##sort()方法永久性地修改了列表元素的排列顺序,默认为升序。
##num=[7,2,1,4,6,3]
##num.sort()
##print(num)
##sorted()函数是返回排序后的列表副本,即列表本身的排序没有发生变化
##num=[2,4,1,3,5]
##print(sorted(num,reverse=True))
##print(num)
##(6)clear()
##clear()方法用于清空列表
##num=['python','study','is']
##print(num)
##num.clear()
##print(num)
##(7)max()、min()、sum()
##num=[7,2,1,4,6,3]
##print(max(num))
##print(min(num))
##print(sum(num))
##(8)len()
##num=[7,2,1,4,6,3]
##print(len(num))
##6.列表切片
## list1=[0 ,1, 2, 3, 4, 5, 6, 7, 8]
## 索引 0 1 2 3 4 5 6 7 8 --> +
## -9 -8 -7 -6 -5 -4 -3 -2 -1 - <--
##切片共有三个参数,用冒号(:)分割开。第一个参数表示切片开始位置(默认为 0),
##第二个参数表示切片截止位置(但不包含该位置),
##第三个参数表示切片的步长(默认为 1)。步长省略时,可以省略最后一个冒号。
##lis=[4,5,6,8,7,9,1,2,4,5,8]
##print(lis[2])
##print(lis[2:5])
##print(lis[:-1])
##print(lis[5:])
##print(lis[4:9:3])
##print(lis[8:2:-2])
##print(lis[::-1])
##print(lis[-1:2:3])
####列表是可变对象,可以通过赋值语句修改列表
##lis=[4,5,6,8,7,9,1,2,4,5,8]
##lis[2:5]=[4,5,6]
##print(lis)
##lis[2:2]=[11]
##print(lis)
##7、列表的元素检查
##lis=[4,5,6,8,7,9,1,2,4,5,8]
##print(2 in lis)
##print(11 not in lis)
##(二)、字符串
####1、字符串的连接
##print('hello'+' '+'world')
##print('6'+str(5))
##print(eval('6')+5)
####2、字符串的复制
##print('aa'*3)
##3、转义符(\)
##在字符串中用反斜杠(\)转义字符,用于表示特殊字符
##\n 换行
##\' 单引号
##\" 双引号
##\\ \
##string='D:\nothing'
##print(string)
##一些字符串中包含反斜杠(\),但不需要转义字符,此时需要用 r 或 R 加在字符串的前面
##string=r'D:\nothing'
##print(string)
##4、字符串切片
##st="Hello world!"
##print(st[:])
##print(st[:11])
##print(st[6:])
##print(st[6:9])
##print(st[3:11:2])
##print(st[::-1])
##字符串是不可变对象,所以不可以对字符串切片赋值
##st="Hello world!"
##st[2:4]='zx' #出错
##5、字符串相关函数和方法
##(1)len(),长度
##s="Python 程序设计"
##print(len(s))
##(2)ord(),对单个字符转换成对应编码
##print(ord('a'))
##print(ord('南'))
##(3)chr(),可将编码转化成对应的字符
##print(chr(65))
##print(chr(21335))
##(4)title(),以首字母大写的方式显示每一个单词,即每个单词的首字母都改为大写
##s="The world is so big,"
##print(s.title())
##(5)upper()、lower(),upper()将字符串的字符全部转换成大写, lower()转换成小写
##s="The world is so big,"
##print(s.upper())
##print(s.lower())
##(6)lstrip()、rstrip()、strip(),分别去除字符串左边、右边、左右两边的空格或指定符号
##s="@python@@"
##print(s)
##print(s.lstrip('@'))
##print(s.rstrip('@'))
##print(s.strip('@'))
##(三)、元组
##元组与列表相似,不同之处在于元组是不可变对象。
##创建和访问元组
##t='a','b'
##print(t)
##t=(3,4,5,6)
##print(t)
##t=(15,)
##print(t)
##元组访问与列表类似
##tp1=(1,2,3,4,5,6)
##print(tp1[3])
##元组的元素不可删除,但可用 del 删除整个元组
##t=(1,2,3)
##del t[1] ##出错
##del t
##3.元组的常用函数
##(1)len()
##(2)max()
##(3)min()
##(4)tuple(),转换成元组
##num=[7,2,1,4,6,3]
##print(tuple(num))
##四、字典和集合
##字典和集合是无序的
##(一)、字典
##1. 字典的操作
##创建字典
##dict1 = {1: 'one', 2:'two', 3:'three'}
##print(dict1)
##
##dict2 = {}
##print(dict2)
##
##dict3 = dict(['a1','b2','c3'])
##print(dict3)
##通过键访问值。
##dict1 = {1: 'one', 2:'two', 3:'three'}
##print(dict1[1])
##增加新的键值对
##dict1 = {'name': 'Tom', 'age':18, 'gender':'Male'}
##dict1['Address'] = 'B105'
##print(dict1)
##修改键所对应的值
##一个键只能对应一个值
##dict1['name'] = 'Jerry'
##print(dict1)
##删除
##删除某一键值对
##dict1 = {'name': 'Tom', 'age':18, 'gender':'Male'}
##del dict1['name']
##print(dict1)
##用 clear 方法删除所有键值对
##dict1.clear()
##print(dict1)
##删除字典对象
##del dict1
##2、字典的操作符 in|not in
##dict1 = {'name': 'Tom', 'age':18, 'gender':'Male'}
##print('age' in dict1)
##print('Tom' not in dict1)
##3、常用方法和函数
##keys()方法获得字典所有的键
##dict1 = {1: 'one', 2:'two', 3:'three'}
##print(dict1.keys())
##print(list(dict1.keys()) )
##values()方法获得字典所有的值
##print(dict1.values())
##print(list(dict1.values()))
##items()方法获得字典所有的键值对
##print(dict1.items())
##print(list(dict1.items()))
##len 函数返回字典的键值对的个数
##print(len(dict1))
##4、字典是可变类型,值可变,键不可变。
##dict1 = {1: 'one', 2:'two', 3:'three'}
##dict1[1]='ONE'
##print(dict1)
##dict1[(0,0)] = 'red'
##print(dict1)
##列表是可变数据类型,不能做字典的键
##dict1[[1,1]] = 'black' #出错
##(二)、集合 set
##1、集合的创建
##集合的元素必须为不可变数据类型,即元素不能为列表、字典或集合 set
##s1={1,2,3,4,5,6}
##print(s1)
##print(type(s1))
##可作为一种去重方式。
##s2 = set([1,2,3,4,5,6,1,2])
##print(s2)
##{}表示空字典,set()表示空集合
##s3=set()
##print(s3)
##print(type({}))
##2、集合常用运算:
##s1 = set('cheeseshop')
##s2 = set('fishshop')
##print(s1)
##print(s2)
##并(|)
##print(s1|s2 )
#交(&)
##print(s1&s2)
#差(-)
##print(s1-s2)
##print(s2-s1)
##四、控制结构
####(一)、选择结构分为三种:单分支、双分支及多分支结构。
####1. 单分支结构:if
####if <条件表达式>:
#### <语句组>
####例:输出两个数中较小的一个数
##a = eval(input('请输入第一个数:'))
##b = eval(input('请输入第二个数:'))
##if a > b:
## a = b
##print(a)
####2. 双分支结构:if - else
####if <条件表达式>:
#### <语句组 A>
####else:
#### <语句组 B>
####例:判断输入的一个整数是奇数还是偶数
##a = int(input('请输入一个数:'))
##if a%2 == 0:
## print("偶数")
##else:
## print("奇数")
####3. 多分支结构:if - elif - else
####if <条件表达式 1>:
#### <语句组 1>
####elif <条件表达式 2>:
#### <语句组 2>
####……
####elif <条件表达式 n>:
#### <语句组 n>
####else:
#### <语句组 x>
####例:输出输入的三个数中较小的一个数
##a = eval(input('请输入第一个数:'))
##b = eval(input('请输入第二个数:'))
##c = eval(input('请输入第三个数:'))
##if a > b:
## if b > c:
## print(c)
## else:
## print(b)
##elif a > c:
## print(c)
##else:
## print(a)
####4. 条件表达式
####<True 部分> if <条件表达式> else <False 部分>
####例:输出两个数中较小的一个数
##a = eval(input('请输入第一个数:'))
##b = eval(input('请输入第二个数:'))
##small = a if a < b else b
##print(small)
####(二)、控制结构之循环结构
####1.for 循环结构
####for <循环变量> in <循环结构>:
#### <循环体>
####else:
#### <语句组>
####例:在给定范围内查找第一个能被 7 整除的整数,查无此数则返回"该范围内找不到符
合要求的数"
##startnum=int(input("请输入查找数据的起始值:"))
##endnum=int(input("请输入查找数据的终止值:"))
##for i in range(startnum, endnum+1):
## if i%7==0:
## print("找到数值{}符合要求".format(i))
## break
##else:
## print("该范围内找不到符合要求的数")
####2.while 循环结构
####while <条件表达式>:
#### <循环体>
####else:
#### <语句组>
####如上例也可写作:
##startnum=int(input("请输入查找数据的起始值:"))
##endnum=int(input("请输入查找数据的终止值:"))
##i=startnum
##while i<=endnum:
## if i%7==0:
## print("找到数值{}符合要求".format(i))
## break
## else:
## i+=1
##else:
## print("该范围内找不到符合要求的数")
####3.break 与 continue 循环控制语句
####(1)break 语句——跳出循环
##for i in range(1,10):
## if i%2==0:
## break
## print(i)
####(2)continue——跳过本轮循环
##for i in range(1,10):
## if i%2==0:
## continue
## print(i,end=' ')
####4.典型算法
####请同学们对上学期所授的素数、因子(因子个数)、升(降)序数、逆序数、最大公约
数(互质、最小公倍数)、armstrong 数、斐波那契数列、阶乘(阶乘和)等算法进行编写整
理,整理时可适当增加难度
####例:整理阶乘,可编写找出给定数的各位数字的阶乘和,并以给定格式进行输出,
####如用户输入 123,则打印出 1!+2!+3!=9

python 题库

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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
##一、选择题
##11)可以部署 Python 环境、运行 Python 脚本的系统是(A)。
##A、各操作系统平台
##B、Linux
##C、Mac Os
##D、Windows
##12)Python 的运算符中**的作用是(D)。
##A、非法符号
##B、乘法运算
##C、操作数取平方
##D、幂运算
##13)以下选项不是 Python 合法变量名的是(C) 。
##A、_maxNum
##B、Eval
##C、2nd_table
##D、VAL
##14)表达式 str(10/2)的结果是(B ) 。
##A、ValueError
##B、"5.0"
##C、'5'
##D、'10/2'
##15)以下语句的执行结果是( A) 。
##ls =[x**2 for x in range(5)]
##print(ls)
##A、[0,1,4,9,16]
##B、[2,4,6,8,10]
##C、[0,2,4,6,8]
##D、[1,4,9,16,25]
##16)表达式 min({3:7,10:5,1:6})的结果是( B) 。
##A、6
##B、1
##C、5
##D、{1:6}
##17)以下语句执行结果是( C) 。
##s = 'HelloWorld'
##print(s[5::-2])
##A、drW
##B、olH
##C、Wle
##D、loo
##18)以下语句执行结果是(D)。
##s ='北京,上海,广州,深圳,'
##print(s.strip(',').replace(',',';'))
##A、北京;上海;广州;深圳;
##B、北京上海 广州 深圳
##C、北京;上海;广州;深圳,
##D、北京;上海;广州;深圳
##19)以下程序的输出结果是(B)。
##import string
##y1 = 'a'
##y2 = 'asdf'
##print(y1 in string.printable,y2 in string.printable)
##A、False True
##B、True False
##C、False False
##D、True True
##20)以下关于控制结构的描述,错误的是(A) 。
##A、break 也可用于跳出 try-except 控制块
##B、break 的功能是跳出当前循环控制块
##C、在 for 结构中使用 continue,会开始遍历下一个元素
##D、Python 的多分支结构里,可以包含多个 elif 语句
##21)以下关于随机运算函数库的描述,正确的是(C)。
##A、Python 的 random 库通过 pip 进行安装库
##B、使用 random.random()生成随机数前,必须先用 random.seed()函数初始化随机数种子
##C、random.randint(a,b)产生一个[a,b]之间的随机整数
##D、random.random(a,b)产生一个[a,b)之间的随机小数
##22)以下代码的输出结果是(D)。
##ls = "ab"
##print("{{}}{:+^4}".format(ls))
##A、+ab+{}
##B、{{}}+ab+
##C、+ab+{}
##D、{}+ab+
#注意:'{{'表示{

# '}}'表示}

##print("{{{:+^4}}}".format(ls))
##23)执行以下程序,输 3.2,然后回车,结果是(C )。
##flag = 0
##try:

## b = eval(input("请输入计算次数:"))

## print(type(b))

##except:

## flag = 1

## print("请输入整数")

##print(flag)
##A、请输入整数 1
##B、<class "int" >0
##C、<class "float">0
##D、<class "float ">1
##24)以下程序的执行结果是(A)。
##a =[12,34,56]
##b =[1,2,3,4]
##def displ(a):

## print('res:', [a])

##b = a
##a.append([5,6])
##displ(b)
##A、res: [[12,34,56,[5,6]]]
##B、res: [12,34,56,[5,6]]
##C、res: [[1,2,3,4,[5,6]]]
##D、res: [12,34,56,5,6]
##25)关于 Python 函数的描述错误的是(A) 。
##A、函数内部使用的全局变量必须用 global 声明
##B、Python 支持可选参数传递,但没有默认值的参数必须定义在有默认值参数的左侧
##C、Python 函数可以没有 return 语句,此时返回值为 None
##D、Python 函数支持用名称传递参数
##26)以下程序的输出结果是(D)。
##def func(x =[], y =[6,7]):

## x.append(8)

## y.append(8)

## return(x+y)

##a, b = [1,2], [3,4]
##t=func(x=a)
##t=func(y=b)
##print(func() ,end=";")
##A、[8,8,6,7,8,8]
##B、[8,6,7,8,8];
##C、[8,6,7,8,8]
##D、[8,8,6,7,8,8];
##27)以下程序的输出结果是(D)。
##def mysort(ss,flag):

## if flag:

## return(sorted(ss,reverse = True))

## else:

## return(sorted(ss,reverse = False))

##ss=[1,2,4,3]
##print(mysort(ss, -1))
##A、[1,2,4,3]
##B、[3,4,2,1]
##C、[1,2,3,4]
##D、[4,3,2,1]
##28)执行以下程序后,要输出 46cd44ab 结果,该执行的选项是(B )。
##ls = ["ab","44","cd","46"]
##ls.reverse()
##A、print("".join(ls[-1::-1]))
##B、print("".join(ls))
##C、print("".join(ls[1:]))
##D、print("".join(ls[-1::]))
##29)以下程序的输出结果是(C) 。
##ss =[2,3,6,9,7,1]
##for i in ss:

## ss.remove(min(ss))

## print(min(ss),end = ",")

##A、1,2,3,6,7,9,
##B、9,7,6,3,2,1,
##C、2,3,6,
##D、1,2,3,6,7,9

##30)以下程序的输出结果是(B)。
##dd = {'a':90,'b':87,'c':93}
##print([[dd[x], x] for x in sorted(dd)])
##A、[[93, 'c],[90, 'a'],[87,'b']]
##B、[[90, 'a'], [87, 'b'],[93, 'c']]
##C、[[87, 'b'],[90, 'a'],[93, 'c']]
##D、[[90, a], [87,b],[93,c]]
##31)以下语句的输出结果是(C) 。
##dd = {'chinese':200,'pe':187,'Gana':930}
##print(sorted(dd.keys()))

##A、dict_keys(['Gana' , 'chinese', 'pe'])
##B、'Gana', 'chinese', 'pe'
##C、['Gana', 'chinese', 'pe']
##D、报错
##32)以下程序的输出结果不可能的选项是(A)。
##import random
##ls =["a","b","c","d"]
##print(ls[int(random.random()*3)])
##A、"d"
##B、"a"
##C、"b"
##D、"a", "b","c"都有可能
##33)以下关于文件的描述,错误的是(A) 。
##A、open()函数的打开模式’t’表示以二进制打开文件
##B、打开文件时,编码方式是可选参数
##C、fo.seek()函数是设置当前文件操作指针的位置
##D、open 函数的打开模式’ a’表示可以对文件进行追加操作
##34 执行以下程序后,文件 a.txt 中的内容是( D) 。
##fo = open("a.txt",'w')
##x =['大学','中学','小学']
##fo.write('\n'.join(x))
##fo.close()
##A、大学\n 中学\n 小学
##B、大学中学小学
##C、'大学',‘\n’,'中学',‘Nn’,小学
##D、大学

## 中学

## 小学

##35)以下方法不是 python 文件操作的选项是(B)。
##A、seek()
##B、socket()
##C、close()
##D、readlines()
##36)以下关于数据组织的维度,以下选项中描述错误的是(C).
##A、JSON 格式能够表达一维数据
##B、字典类型可以表示具有复杂关系的高维数据
##C、列表只能表示一维数据
##D、CSV 文件可以用来存储二维数据
##37)turtle 库的控制顺时针转的函数是(C) 。
##A、penup()
##B、set()
##c、right()
##D、pencolor()
##38)关于 Pyinstaller 工具,下列说法正确的是(A )。
##A、只能处理 UTF-8 编码形式的 Python 源文件
##B、生成单独的可执行文件时,图片等文件资源不能一并打包到可执行文件中
##C、不能为生成的可执行文件指定图标
##D、不能生成带有动态链接库的可执行文件
##注:Pyinstaller 是 python 的一个第三方库。可将 python 源文件(即.py 文件)打包,变
成直接可运行的可执行文件。

## 执行:在 cmd 窗口,程序(如 Verify.py)所在的路径下,pyinstaller -F Verify.py 即可

##39)Python 机器学习方向的第三方库是(B )。
##A、openpyxl
##B、tensorflowo
##C、Flask
##D、PIL
##40 )Python 网络爬虫开发方向的第三方库是(C)。
##A、Django
##B、Theano
##C、scrapy
##D、Tkinter
##二、基本操作题(15 分)
##41)在考生文件夹下有个文件 PY101.py,在横线处填写代码,完成如下功能。
##接收用户输入的一个浮点数,输出这个浮点数的小数部分各字符的和,
##以 10 为宽度,靠右显示,采用星号*填充。例如:
##输入:1234.5678
##输出:
##********26
##s = input("请输入一个小数: ")
##s = s[::-1]
##____________
##for c in s:

## if c == '.':

## ____________

## cs += eval(c)

##print('{____________}'.format(cs))
##{<参数序号>:<格式控制标记>}
##格式控制标记包括:<填充><对齐><宽度><,><.精度><类型>等六个字段,都是可选
项。
##s = input("请输入一个小数: ")
##s = s[::-1]
##cs=0
##for c in s:

## if c == '.':

## break

## cs += eval(c)

##print('{:*>10}'.format(cs))
##42)在考生文件夹下有个文件 PY102.py,在横线处填写代码,完成如下功能。
##time 库是 Python 语言中与时间处理相关的标准库,time 库中 ctime()函数能够将
##一个表示时间的浮点数变成人类可以理解
##的时间格式,示例如下:
##import time
##print(time.ctime(1519181231.0))
##输出结果是:Web Feb 21 10:47:11 2018
##请获得用户输入时间,提取并输出其中的小时信息。以上述时间为例,应输出 10。
##import time
##t = input("请输入一个浮点数时间信息: ")
##s = time.ctime(____________)
##ls = s.split()
##print(____________)
##import time
##t = input("请输入一个浮点数时间信息: ")
##s = time.ctime(eval(t))
##ls = s.split()
##print(ls[3].split(':')[0])

##43)在考生文件夹下有个文件 PY103.py,在横线处填写代码,完成如下功能。
####以 26 个小写字母和 0-9 数字为基础,以用户输入的数字为种子,随机生成
####10 个 8 位密码,并将每个密码在单独一行打印输出。例如:
####输入:
####125
####输出:
####potlwjta
####ej460gqs
####k5l5jdr8
####1blked1f
####y37c4mhx
####1oa18pv5
####pz6r37t7
####xegd1ql3
####l2w0ksh6
####pxuybhp9
##import random
##
##s = input("请输入随机种子: ")
##ls = []
##for i in range(26):

## ls.append(chr(ord('a')+i))

##for i in range(10):

## ls.append(chr(____________))

##
##random.seed(____________)
##for i in range(10):

## for j in range(8):

## print(____________,end='')

## print()

##import random
##
##s = input("请输入随机种子: ")
##ls = []
##for i in range(26):

## ls.append(chr(ord('a')+i))

##for i in range(10):

## ls.append(chr(ord('0')+i))

##
##random.seed(eval(s))
##for i in range(10):

## for j in range(8):

## print(ls[random.randint(0,35)],end='')

## print()

##import random
##random.seed(25)
##for i in range(10):

## print(random.randint(10,1000))

##三、简单应用
##44)在考生文件夹下有个文件 PY201.py,在横线处填写代码,完成如下功能。
####利用 random 库和 turtle 库,在屏幕上绘制 3 个黑色的正方形,正方形
####的左下角点坐标和正方形边长由 randint()函数产生,参数在代码中给出。
####效果如下图所示。
##import turtle as t
##import random as r
##r.seed(1)
##t.pensize(2)
##for i in range(3):

## length = r.____________(20,80)

## x0 = r.randint(-100, 100)

## y0 = r.randint(-100, 100)

##

## t.penup()

## t.goto(____________)

## t.____________

## for j in range(4):

## t.____________(length)

## t.____________(90*(j+1))

##t.done()
##import turtle as t
##import random as r
##r.seed(1)
##t.pensize(2)
##for i in range(3):

## length = r.randint(20,80)

## x0 = r.randint(-100, 100)

## y0 = r.randint(-100, 100)

##

## t.penup()

## t.goto(x0,y0)

## t.pd()

## for j in range(4):

## t.fd(length)

## t.seth(90*(j+1))

##t.done()
##四、综合应用
##45)在考生文件夹下有个文件 PY202.py,在省略号处填写一行或多行代码,完成如下功能。
##同时,在考生文件夹下有个文件 out.txt,其中有一些数据库操作功能的执行时间信息,如
下所示:
##starting 0.000037 2.102
##After opening tables 0.000008 0.455
##System lock 0.000004 0.227
##Table lock 0.000008 0.455
##...
##其中第 1 列是操作的名字,第 2 列是操作所花费的时间,单位是秒,第 3 列是操作时间
占全部过程的百分比,
##字段之间用逗号','隔开。
##修改考生文件夹下的文件 PY202.py,读取 out.tut 文件里的内容,统计所有操作所花费的
时间总和,
##并输出操作时间百分比最多的三个操作所占百分比的值,及其对应的操作名称,
##显示在屏幕上,如下所示:
##the total execute time is 0.0017
##the top 0 percentage time is 46.023,spent in "Filling schema table" operation
##...
##sumtime = 0
##percls = []
##ts = {}
##with open('out.txt', 'r') as f:
##

## ...

##print('the total execute time is ', sumtime)
##tns = list(ts.items())
##tns.sort(key=lambda x: x[1], reverse=True)
##for i in range(3):

## print('the top {} percentage time is {}, spent in "{}" operation'.format(i, tns[i][1],tns[i][0]))

##sumtime = 0
##percls = []
##ts = {}
##with open('out.txt', 'r') as f:

## for line in f:

## linelist=line.strip().split(',')

## ts[linelist[0]]=eval(linelist[2])

## sumtime+=eval(linelist[1])

## sumtime=round(sumtime,4)

##print('the total execute time is ', sumtime)
##
##tns = list(ts.items())
##tns.sort(key=lambda x: x[1], reverse=True)
##for i in range(3):

## print('the top {} percentage time is {}, spent in "{}" operation'.format(i, tns[i][1],tns[i][0]))

##46)词频统计并输出。要求如下:
##(1)对"红楼梦.txt"中文本进行分词,并对人物名称进行归一化处理,仅归一化以下内容:

## 凤姐、凤姐儿、凤丫头归一为凤姐;宝玉、二爷、宝二爷归一为宝玉;黛玉、颦儿、林妹

妹、黛玉道归一为黛玉﹔

## 宝钗、宝丫头归一为宝钗;贾母、老祖宗归一为贾母;袭人、袭人道归一为袭人﹔

## 贾政、贾政道归一为贾政﹔贾琏、琏二爷归一为贾琏。

##(2)不统计“停用词.txt"文件中包含词语的词频。
##(3)提取出场次数不少于 40 次的人物名称,将人物名称及其出场次数按照递减排序,保
存到 result.csv 文件中,
##出场次数相同的,则按照人物名称的字符顺序排序。示例如下:
##宝玉,123
##凤姐,101

## …(略)

##其中,人物名称与出场次数之间采用英文逗号分隔,无空格,每组信息—行。
##import jieba
##f = "红楼梦.txt"
##sf = "停用词.txt"
##......

## items.sort(key=lambda x:x[1], reverse=True)

## 此行语句可以对 items 列表进行递减排序

import jieba
f = "红楼梦.txt"
sf = "停用词.txt"
f1=open(f,encoding="utf-8")
datas=f1.read()
f1.close()
f2=open(sf,encoding="utf-8")
words=f2.read()
f2.close()
data=jieba.lcut(datas)
d={}
word=["一个","如今","一面","众人","说道","只见","不知",
"两个","起来","二人","今日","听见","不敢","不能",
"东西","只得","心中","回来","几个","原来","进来",
"出去","一时","银子","起身","答应","回去"]
for i in data:
if len(i)<2 or i in word or i in words:
continue
if i in ["凤姐","凤姐儿","凤丫头"]:
i="凤姐"
elif i in ["宝玉","二爷","宝二爷"]:
i="宝玉"
elif i in ["黛玉","颦儿","林妹妹","黛玉道"]:
i="黛玉"
elif i in ["宝钗","宝丫头"]:
i="宝钗"
elif i in ["贾母","老祖宗"]:
i="贾母"
elif i in ["袭人","袭人道"]:
i="袭人"
elif i in ["贾政","贾政道"]:
i="贾政"
elif i in ["贾琏","琏二爷"]:
i="贾琏"
d[i]=d.get(i,0)+1
l=list(d.items())
l.sort(key=lambda x:(x[1],x[0]), reverse=True)
f=open("result.csv",'w')
for i in l:
if i[1]<40:
break
f.write(i[0]+','+str(i[1])+'\n')
f.close()

python基本方法

1
2
3
##安装python第三方库
pip install -i https://pypi.tsinghua.edu.cn/simple jieba
pip install -i https://pypi.tsinghua.edu.cn/simple wordcloud
1
2
3
4
5
6
7
8
9
10
11
12
13
14
##wordcloud
wordsall = ' '.join(words)

wc = WordCloud(
font_path = 'msyhbd.ttc',
background_color = 'white',
width = 800,
height = 600,
max_font_size = 100,
min_font_size = 10,
mode = 'RGBA'
)
wc.generate(wordsall)
wc.to_file('dream.png')
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
f = open('八十天环游地球.txt',encoding = 'utf-8')
allLines = f.readlines()
f.close()

chaptNos = [] ##[0,70,106,...]
for lineNo in range(len(allLines)):
if allLines[lineNo][0] == '第':
chaptNos.append(lineNo)

chaptCons = []
for i in range(len(chaptNos) - 1):
chaptCons.append(allLines[chaptNos[i]:chaptNos[i + 1]])
chaptCons.append(allLines[chaptNos[-1]:])

##chaptCons内记录了各个章节的行和组成
for chapt in chaptCons:
alltxt = ''
for line in chapt:
alltxt += line
words = jieba.cut(alltxt)
wordDic = {} ##{'路路通':1,...}
for word in words:
if len(word) > 2:
if word not in wordDic:
wordDic[word] = 1
else
wordDic[word] += 1
wordList = []
for key in wordDic:
wordList.append([key,wordDic[key]])
wordList.sort(key = lambda x:x[1])
print(chapt[0].split[0], wordList[-1][0], wordList[-1][1])
1
2
3
4
5
6
7
8
9
10
11
12
13
14
##价格文件的变化
f = open('price.csv')
priceL = []
for line in f:
priceL.append(line.strip().split(','))
f.close()

f = open('priceResult.csv', 'w')
f.write(','.join(priceL[0]) + '\n')
for i in range(1,len(priceL)):
for j in range(1,len(priceL[i])):
priceL[i][j] += '%'
f.write(','.join(priceL[i]) + '\n')
f.close()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
##选举
import os

fp = '<filepath>'
files = os.listdir(fp)
voteD = {}
for file in files:
abfile = fp + '\\' + file
f = open(abfile)
name = f.read().split()
f.close
if len(name.split()) == 1:
if name not in voteD:
voteD[name] = 1
else:
voteD[name] += 1
voteLst = []
for name in voteD:
voteLst.append((name, voteD[name]))
voteLst.sort(key = lambda x:x[1], reverse = True)
print(voteLst[0][0])
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
##生成100个三位整数并保存,再从该文件读取所有的数,记录并存档其中的素数

import random

f = open('data.txt', 'w')
for i in range(100):
n = random.randint(100,999)
f.write(str(n) + ',')
f.close()

def IsPrime(n):
if n >=2:
for i in range(2,n):
if n % i == 0:
return False
return True
else:
return False

f = open('data.txt')
nums = f.read().strip().split(',')
f.close()

f = open('result.txt', 'w')
for num in nums:
if len(num) == 3:
if IsPrime(int(num)):
f.write(num + '|')
f.close()
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
##二维文件处理(CSV)
f = open('data.csv')
for line in f:
datas = line.strip().split(',')
print(datas)
f.close()

import random

f = open('rnd.csv', 'w')
for line in range(100):
n = random.randint(1,100)
f.write(str(n) + ',')
if (i + 1) % 10 == 0:
f.write('\n')
f.close()

f = open('rnd_1.csv', 'w')
rndL = []
for i in range(100):
n= random.randint(1,100)
rndL.append(str(n))
if (i + 1) % 10 == 0:
ws = ','.join(rndL) + '\n'
f.write(ws)
rndL = []
f.close()
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
35
36
37
38
39
40
41
42
43
44
45
##新冠数据分析
##1、按年龄段统计病例人数
f = open('covid-19.csv')
lines = f.readlines()
f.close()

ageD = {}
for i in range(1, len(lines)):
datas = lines[i].strip().split(',')
age = datas[6]
if age not in ageD:
ageD[age] = 1
else:
ageD[age] += 1

ageL = []
for age in ageD:
ageL.append((age, ageD[age]))
ageL.sort(key = lambda x:x[1])
maxCnt = ageL[-1][1]
for item in ageL:
if item[1] == maxCnt:
print(item[0])

##2、统计各年龄段病例的死亡率并排序
f = open('covid-19.csv')
lines = f.readlines()
f.close()

ageD = {}
for i in range(1, len(lines)):
datas = lines[i].strip().split(',')
age = datas[6]
death = datas[9]

if age not in ageD:
ageD[age] = [1,0]
else:
ageD[age][0] += 1

if death == 'Yes':
ageD[age][1] += 1

for age in ageD:
print('年龄段:{0} 死亡率{1:.2f}%'.format(age,ageD[age][1]/ageD[age][0]*10))
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
##2023.4.10
##1、找出排名前十的同学,并记录在文件中
f = open('score.txt')
allData = f.readlines()
f.close()

top10 = []
top10Index = []
i = 0
for line in allData:
stulst = line.strip().split()
grade = 0
for score in stulst[2:]:
grade += int(score)
top10.append((line, grade))
top10Index.append((i,grade))
i += 1
top10.sort(key = lambda x:x[1], reverse = True)
top10Index.sort(key = lambda x:x[1], reverse = True)

f = open('ret0.txt', 'w')
for i in range(10):
Index = top10Index[i][0]
f.write(allData[Index])
f.close()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
##2、选奖学金
fr = open('ret0.txt')
fw = open('ret.txt', 'w')
for line in fr:
lst = line.strip().split()
#判断是否及格
grade = True
for score in lst[2:]:
if int(score) < 60:
grade = False
break
if grade == True:
fw.write(' '.join(lst[0:2]) + '\n')
fw.write('{}{}\n'.format(lst[0], lst[1]))
fw.close()
fr.close()
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
##根据数据计算
##确诊人数最多的一天
##确诊人数最多的一个月
##确诊变化的增长率与降低率最高的一天

##1
f = open('shanghai.csv', encoding = 'utf-8')
lines = f.readlines()
f.close()

maxV = 0
for i in range(1,len(lines)):
lst = lines[i].strip().split(',')
curV = int(lst[1])
if curV > maxV:
maxV = curV

for i in range(1, len(lines)):
lst = lines[i].strip().split(',')
curV = int(lst[1])
if curV == maxV:
print(lst[0])

##2
dateVD = {}
for i in range(1, len(lines)):
lst = lines[i].strip().split(',')
month = lst[0][:7]
value = int(lst[1])
if month not in dateVD:
dateVD[month] = value
else:
dateVD[month] += value

dateLst = []
for month in dateVD:
dateLst.append((month, dateVD[month]))
dateLst.sort(key = lambda x:x[1], reverse = True)
maxV = dateLst[0][1]

for item in dateLst:
if item[1] == maxV:
print(item[0])

##3
dateD = {}
for i in range(1, len(lines) - 1):
lst = lines[i].strip().split(',')
day = lst[0]
value = int(lst[1])
preValue = int(lines[i + 1].strip().split(',')[1])
if preValue == 0:
rate = None
else:
rate = (value - preValue) / preValue
dateD[day] = rate

dateLst = []
for day in dateD:
if dateD[day] != None:
dateLst.append((day, dateD[day]))
dateLst.sort(key = lambda x:x[1])
minV = dateLst[0][1]
minV = dateLst[-1][1]

for item in dateLst:
if item[1] == minV:
print('降低率最高的日期:{}({:.2f})'.format(item[0], item[1]))
if item[1] == maxV:
print('增长率最高的日期:{}({:.2f})'.format(item[0], item[1]))
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
##Json数据处理(using 'eval()' fct 可以把字符串转为一个表达式,或者生成列表)
#linelist = eval('[' + line + ']')
#print(linelist, type(linelist), linelist[0])

import os

def ReadJson(fn):
retL = []
f = open(fn, encoding = 'utf-8')
for line in f:
retL.append(eval(line.strip())[0])
f.close()
return retL

def ReadFiles(fp):
retAll = []
files = os.listdir(fp)
for file in files:
fa = fp + '\\' + file
retT = ReadJson(fa)
retAll += retT
return retAll

fp = '<filepath>'
ret = ReadFiles(fp)
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
##分析微博Json
##1、发表源种类、数量及所占比例,从大到小排列
srcD = {}
total = 0
for item in ret:
src = item['source']
if src not in srcD:
srcD[src] = 1
else:
srcD[src] += 1
srcD[src] = srcD.get(src,0) + 1
total += 1
#统计和排序
srcL = []
for src in srcD:
srcL.append((src,srcD[src], srcD[src]/total))
srcL.sort(key = lambda x:x[1], reverse = True)
for item in srcL:
print('发表源:{}数量:{}占比:{:.2f}%'.format(item[0], item[1]......))

##2、评论最多的微博的内容和点赞最多的微博内容
comL = []
for item in ret:
commentcnt = int(item['sth1'])
content = item['sth2']
comL.append((sth1,sth2))
comL.sort(key = lambda x:x[0], reverse = True)
maxCount = comL[0][0]
for item in comL:
if item[0] == maxCount:
print('发表的信息({}):{}'.format(maxCount, item[1])) #comment max

#sth1可以更换为其他键从而获取赞最多的评论,函数

def getContent(key):
comL = []
for item in ret:
commentcnt = int(item[key])
content = item['sth2']
comL.append((sth1,sth2))
comL.sort(key = lambda x:x[0], reverse = True)
return comL
maxCount = comL[0][0]
## for item in comL: 不应在函数内部print
## if item[0] == maxCount:
## print('发表的信息({}):{}'.format(maxCount, item[1]))

print('评论最多')
#函数生成
print('___________') #dividing line
print('most zans')
##.....
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
##检索,keywords用','隔开,并且有多种检索逻辑
def Query(allitems, keywords, method):
keyList = keywords.split(',')
i = 1
for item in allitems:
if method == '&':
ret = True
for key in keyList:
if key not in item['content']:
ret = False
break
else:
ret = False
for key in keyList:
if key in item['content']:
ret = True
break
if ret == True:
print('{}:{}'.format(i, item['content']))
i += 1

keywords = input('请输入您关心的话题:')
Query(ret, keywords, '|')

Python 函数

生成Markdown插入图片代码

1
2
3
4
5
6
7
import os
pre_path=input('Please input your basic path:')
dirs=os.listdir()
for file in dirs:
path='!['+file+']'+'('+pre_path+file+')'
print('### ',file[:-4])
print(path)

素数判断函数

1
2
3
4
5
6
7
def IsPrime(n):
if n<2:
return False
for i in range(2,n):
if n % i==0:
return False
return True

计算每位数的阶乘的函数

1
2
3
4
5
6
7
8
9
def Factorial(n):
sum1 = 0
for i in str(n):
i = int(i)
fact = 1
for j in range(2,i+1):
fact *= j
sum1 += fact
return sum1

寻找互质数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
for m in range(100,1000):
guam = m
nstr = str(m)
n = nstr[::-1]
if n[0] == '0':
continue
else:
n=eval(n)
guan = n
r = m%n
while r!= 0:
m=n
n=r
r=m%n
if n == 1:
print('{}与{}互质'.format(guam,guan))

找出规定范围内每位数都是素数的数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
for n in range(100,1000):   
nstr=str(n)
for s in nstr:
ints=eval(s)
if ints<2:
break
for i in range(2,ints):
if ints%i==0:
flag=False
break
else:
flag=True
if not flag:
break
else:
print(n)

寻找范围内的完数

1
2
3
4
5
6
7
8
9
for n in range(10,10000):
st=""
sum1=0
for i in range(1,n):
if n%i==0:
st=st+str(i)+"+"
sum1+=i
if sum1==n:
print("{}={}".format(n,st[:-1]))

最小公倍数

1
2
3
4
5
6
7
8
9
m = int(input("Please input the first num:"))
n = int(input("Please in put the second num:"))
p = m*n
r = m%n
while r != 0:
m = n
n = r
r = m % n
print(p//n)

寻找4位降序数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import random
ls=[]
for i in range(30):
x=random.randint(1000,9999)
ls.append(x)
print(ls)
count=0
for t in ls:
s=str(t)
for j in range(len(s)-1):
if s[j]<=s[j+1]:
break
else:
print(s)
count+=1
if count==0:
print("无降序数")

实现读取json文件功能的部分函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import os

def ReadJson(fn):
retL = []
f = open(fn, encoding = 'utf-8')
for line in f:
retL.append(eval(line.strip())[0])
f.close()
return retL

def ReadFiles(fp):
retAll = []
files = os.listdir(fp)
for file in files:
fa = fp + '\\' + file
retT = ReadJson(fa)
retAll += retT
return retAll

获取Json字典中值数量最多的项目

1
2
3
4
5
6
7
8
9
def getContent(key):
comL = []
for item in ret:
commentcnt = int(item[key])
content = item['sth']
comL.append((key,sth))
comL.sort(key = lambda x:x[0], reverse = True)
return comL
maxCount = comL[0][0]

直角坐标系两点求距离

1
2
3
4
5
6
7
8
print("A、B两点坐标分别为A(x1,y1)、B(x2,y2)")
a=input("请输入x1:")
b=input("请输入y1:")
c=input("请输入x2:")
d=input("请输入y2:")
print("A和B两点之间的距离为:",end=" ")
print(round(pow(pow(eval(a)-eval(c),2)+pow(eval(b)-eval(d),2),0.5),1))
##上述式子由平面直角坐标系距离公式写出

通过if-elif-else计算税

1
2
3
4
5
6
7
8
9
10
11
12
income = eval(input('请输入月收入:'))
if income <= 2000:
tax = 0
elif income > 2000 and income <=3000:
tax = ( income - 2000 ) * 0.05
elif income > 3000 and income <=4000:
tax = ( income - 3000 ) * 0.15 + 50
elif income > 4000 and income <=5000:
tax = ( income - 4000 ) * 0.25 + 200
else:
tax = ( income - 5000 ) * 0.35 + 450
print('月收入{:.2f},调节税为{:.2f}'.format(income,tax))

生成指定项数的斐波拉契数列

1
2
3
4
5
6
7
8
9
10
11
12
list0 = [1,1]
terms = eval(input('斐波拉契数列的项数:'))
for i in range(terms-2):
list0.append(list0[-2]+list0[-1])
print(list0)
for t in range(2,terms-1): ##t表示index
num = list0[t] ##num为从列表中取出的数
for k in range(2,t): ##k表示可能的因数
if num%k == 0:
break
else:
print(num)

将分钟转化为X小时X分钟

1
2
3
4
5
6
7
8
9
min_time = eval(input('please input you num(minute):\n'))
hour = 0
while True:
if min_time >= 60 :
min_time -= 60
hour += 1
else:
break
print('{}hours and {}minutes'.format(hour,min_time))

try-except-finally

1
2
3
4
5
6
7
try:
try_suite ##监控这里的异常
except Exception:
except_suite ##异常处理代码
else:
finally:
finally_suite ##无论如何都执行

若有一个else,至少有一个except

format方法

1
2
3
4
5
6
7
list1=[1,2,3,4]             ##stuid
list2=[98,67,89,80] ##c-score
list3=[100,90,83,62] ##m-score
list4=[90,98,100,82] ##e-score
stuid=input("请输入学生的学号:")
listid=eval(stuid)-1 ##index
print("该学生成绩为语文{0},数学{1},英语{2},总分{3}。".format(list2[listid],list3[listid],list4[listid],list2[listid]+list3[listid]+list4[listid]))

if-else实现注册功能

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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
####operation:1register 2login 3changepwd 4logout
####在break之前为mode赋值实现切换功能
prompt = "Select the appropriate operation: 1:register 2:login 3:change-password 4:exit\n"
users = {}
mode = 0
while True:
if mode == 0:
print("We will use the 'num-' -like form to indicate what you are doing.")
mode = input(prompt)
elif mode == "1":
while True:
user = input("1-The user will now continue to be created.\n1-Type ## to end.\n\n1-Please input your username.\n")
if user == "##":
mode = 0 ####程序初始化
break
pwd = input("1-Please input your password now.\n")
while True:
if user == pwd:
print("1-Password is too weak!")
pwd = input("1-Please input your password now.\n") ####密码强度检查
else:
break
if user not in users:
users[user] = pwd
else:
print("1-@@@Alert!The user already exists!")
elif mode == "2":
while True:
user = input("2-Please input your username.\n2-Type ## to end.\n")
if user == "##":
mode = 0 ####初始化
break
if user in users:
pwd = input("2-Please input your password now.\n")
if users[user] == pwd:
print("2-Login successfully!")
else:
print("2-Wrong password provided!")
else:
mode = input("2-The user does not exist.\n2-Enter the function number provided before to switch to another function.\n")
break ####实现功能跳转。
break
elif mode == "3":
while True:
user = input("3-Please input your username.\n3-Type ## to end.\n")
if user == "##":
mode = 0 ####初始化
break
if user in users:
pwd = input("3-Please input your original password now.\n")
if users[user] == pwd:
pwd1 = input("3-Correct password!\n3-Now please input the new password.\n")
while pwd1 == pwd:
pwd1 = input("3-The password is the same as the old one. Please re-enter it.\n")
if pwd1 == input("3-Please input your new password again!\n"):
users[user] = pwd1
print("3-Password updated successfully!")
else:
print("3-Wrong password provided!")
else:
mode = input("3-The user does not exist.\n3-Enter the function number provided before to switch to another function.\n")
break ####实现功能跳转。
break
else:
break

获取hitokoto的api内容并且将其保存至HTML文件中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import time
import requests
start_num = eval(input('define start_num:\n'))
file_name = str(start_num) + '.html'
while True:
stapi = requests.get('https://v1.hitokoto.cn/?encode=text')
if stapi.text == '' :
break
#### saying = str(input('define saying for {}.html:\n'.format(start_num)))
#### if saying == '' :
#### print('Empty!Empty!Empty!')
#### saying = str(input('define saying for {}.html:\n'.format(start_num)))
##file_process-start
f = open( 'D:\stapi\%s.html' % (start_num,) , 'x' , encoding='utf-8' )
#### f.write( '%s' % (saying,) )
f.write( stapi.text )
f.close()
##file_process-end
#### print('success!{}.html:{}'.format(start_num,saying))
print('success!{}.html:{}'.format(start_num,stapi.text))
start_num += 1
time.sleep(1)

format用法指南

<模板字符串>.format(<逗号分隔的参数>)

"I'm {}, I'm {} years old.".format('Tom','five')

在模板字符串中,大括号内有如下方法:{<参数序号>:<格式控制标记>}如模板字符串中有多个{},且{}中没指定序号,按出现顺序对应参数。格式控制标记顺序:<填充><对齐><宽度><,><.精度><类型>等六个字段

<填充>:修改默认填充字符。

<对齐>:<左对齐,>右对齐,^居中对齐。

<宽度>:输出字符宽度。如实际位数小于指定宽度,默认以空格补充。反之,则按实际位数输出。

<,>:用于显示数字类型的千位分隔符。

<.精度>:对于浮点数,精度表示小数部分的有效位数;对于字符串,精度表示输出的最大长度,如果实际长度大于精度,仍输出精度指定的长度。

<类型>:表示输出整数和浮点数的格式规则。

1.对于整数类型,输出格式主要包括:b(二进制),d(十进制),o(八进制),x(小写十六进制),X(大写十六进制)等。

2.对于浮点数类型,输出格式包括:e(小写e指数形式),E(大写E指数形式),f(标准浮点形式),%(百分比)。

附:format语法PDF

报错解释

SyntaxError:解释器语法错误
NameError:尝试访问一个未申明的变量
TypeError 数据类型不匹配
KeyError:请求一个不存在的字典关键字
IOError:输入输出错误(打开的文件不存在)
AttributeError: 尝试访问未知的对象属性
KeyError不存在字典关键字
ZeroDivisionError:除数为零
FileNotFoundError打开文件不存在
IndexError:请求的索引超过序列范围

 Comments
Comment plugin failed to load
Loading comment plugin