Python123 历年经典1-13 程序题 笔记
因版权问题,这里不放题只有结果,仅供计算机二级考试复习使用。
历年经典 01
第一题:基本操作题 13-25767
随机数生成
import random
random.seed(123)
for i in range(10):
x = random.randint(1,999)
print(x,end=",")
第二题:基本操作题21-25769
随机选择列表项
import random
brandlist = ['华为','苹果','诺基亚','OPPO','小米']
random.seed(0)
i = random.randint(0,4)
name = brandlist[i]
print(name)
第三题:基本操作题21-25769
基本编程题72-25821
s = input()
print('{}'.format(s[::-1]),end="")
print(len(s))
第四题:圆中方 简单应用题8-4
#PY201.py
import turtle
turtle.pensize(2)
for i in range(4):
turtle.fd(200)
turtle.left(90)
turtle.left(-45)
turtle.circle(100*pow(2,0.5))
第五题:村长选举 5-5第一问 #68600
D.get(vote[:-1],0)
f = open("name.txt", encoding="utf-8")
names = f.readlines()
f.close()
f = open("vote.txt", encoding="utf-8")
votes = f.readlines()
f.close()
D = {}
NUM = 0
print(votes)
for vote in votes:
num = len(vote.split()) # 分解成列表,并求列表长度(元素个数)
if num == 1 and vote in names: # 仅一个且在姓名中,有效
D[vote[:-1]] = D.get(vote[:-1], 0) + 1 # 学会这个用法!
NUM += 1
else:
with open("vote1.txt", "a+", encoding="utf-8") as fi:
fi.write("{}".format(vote)) # 如果无效,保存到vote1文件内
第六题:村长选举 5-5 第二问 #32582
list.sort(cmp=None, key=None, reverse=False)
True 降序——排序是大的在前
l.sort(key=lambda s: s[1], reverse=True)
指使用第1(二)个作为排序指标
l = list(D.items()) # 字典类型化为列表,列表里有两层
l.sort(key=lambda s: s[1], reverse=True) # sort用法!
name = l[0][0]
score = l[0][1]
print("有效票数为:{} 当选村民为:{},票数为:{}".format(NUM, name, score))
第七题 《命运三问》 问题一 1-6#26261
首先文件要.read
其次是用到d.get()
然后是list(d.items()) 变成列表以排序
接着 .sort 排序
最后取0值作为结果输出
txt = open("命运.txt", "r", encoding="utf-8").read() #正式考试可以不用指定编码,用系统默认。
for ch in ",。?:":
txt = txt.replace(ch, "")
d = {}
for ch in txt:
d[ch] = d.get(ch, 0) + 1
ls = list(d.items())
ls.sort(key=lambda x: x[1], reverse=True)
a, b = ls[0]
print("{}:{}".format(a, b))
第八题 《命运三问》 问题二 1-6#26267
end = '\n' 默认end就是换行,所以不用写;要不换行就是end = ''
这里打印[2] 我没看懂,不是打印名字吗?
txt = open("命运.txt", "r", encoding="utf-8").read()
for ch in '\n':
txt = txt.replace(ch, "")
d = {}
for ch in txt:
d[ch] = d.get(ch, 0) + 1
ls = list(d.items())
ls.sort(key=lambda x: x[1], reverse=True) # 此行可以按照词频由高到低排序
for i in range(10):
print(str(ls[i])[2], end="")
第九题 《命运三问》 问题三 1-6#26269
不包含空格和回车,所以循环排除的是"\n"
str().strip() 因为是字符串操作符,所以要str();strip()括号内的东西存在就可以,例如strip(12),会删掉头尾的12和21。
记得文件用完要关f.close()
看不懂为什么取第二个和第五个字符开始,不是第0是字符,第2:是数字吗?
txt = open("命运.txt", "r", encoding="utf-8").read()
for ch in ' \n':
txt = txt.replace(ch, "")
d = {}
for ch in txt:
d[ch] = d.get(ch, 0) + 1
ls = list(d.items())
ls.sort(key=lambda x: x[1], reverse=True) # 此行可以按照词频由高到低排序
string = ""
for i in range(len(ls)):
s = str(ls[i]).strip("()")
if i < len(ls) - 1:
string = string + s[1] + ':' + s[5:] + ','
else:
string = string + s[1] + ':' + s[5:]
f = open("命运-频次排序.txt", "w", encoding="utf-8")
f.write(string)
f.close()
历年经典 02
2.1 格式化输出
n = eval(input("请输入正整数:"))
print("{:*>15}".format(n))
2.2 分词
import jieba
txt = input("请输入一段中文文本:")
ls=jieba.lcut(txt)
for i in ls[::-1]:
print(i,end='')
2.3 向量乘积
a = [3,6,9]
b = eval(input()) #例如:[1,2,3]
s =0
for i in range(3):
s += a[i]*b[i]
print(s)
2.4 多边形
import turtle
turtle.pensize(2)
d = 0
for i in range(1,6):
turtle.fd(100)
d += 72
turtle.seth(d)
2.5 分词去重
这里集合居然可以排序
写数据的时候记得要么用.join()要么 +'\n'换行
import jieba #导入中文分词库
f = open('out1.txt','w') #以写的方式打开out1.txt文件
fi = open("data.txt","r",encoding="utf-8") #以读的方式打开data.txt文件
#使用jieba.lcut()对data.txt文件读出字符串进行中文分词,返回列表lst
lst = jieba.lcut(fi.read())
s = set(lst) #使用set函数将列表lst转换为集合,实现元素去重
s1 = sorted(s) #将列表按字符顺序排序
ls = list(s1) #将集合重新变成列表ls
for item in ls: #遍历去重后ls每一个元素
if len(item) >=3:
f.write(item + "\n") #将符合条件的字符串写入out1.txt中
fi.close() #关闭文件fi
f.close() #关闭文件f
2.6 十二星座
要使用.replace('\n','')去掉换行符
要使用ls.append(line.split(',')) 将每行数据分割后转换成一个列表,列表套列表
fo = open("PY301-SunSign.csv","r",encoding='utf-8')
ls = []
for line in fo.readlines():
line = line.replace("\n","")
ls.append(line.split(","))
s = input("请输入星座中文名称(例如, 双子座):")
for i in range(len(ls)):
if s == ls[i][1]:
print("{}的生日位于{}-{}之间".format(s,ls[i][2],ls[i][3]))
2.7 十二星座 之 查找
注意while循环需要在while外有一个input(),然后是while的第一个缩进有一个input()
fo = open("PY301-SunSign.csv", 'r',encoding='UTF-8')
ls = []
for line in fo.readlines():
ls.append(line.replace("\n", '').split(','))
# li = line.strip().split(',')
sall = input('请输入星座序号(例如,5 10):')
while sall != '':
lsNum = sall.split()
for s in lsNum:
for i in range(len(ls)):
if s == ls[i][0]:
print("{}({})的生日是{}月{}日至{}月{}日之间".format(ls[i][1],ls[i][4],ls[i][2][:-2],ls[i][2][-2:],ls[i][3][:-2],ls[i][3][-2:]))
sall = input('请输入星座序号(例如,5 10):')
2.8 十二星座
fo = open("PY301-SunSign.csv", 'r',encoding='UTF-8')
ls = []
for line in fo.readlines():
ls.append(line.replace("\n", '').split(','))
# li = line.strip().split(',')
sall = input('请输入星座序号(例如,5 10):')
while sall != '':
lsNum = sall.split()
for s in lsNum:
if 1 <= int(s) <=12:
for i in range(len(ls)):
if s == ls[i][0]:
print("{}({})的生日是{}月{}日至{}月{}日之间".format(ls[i][1],ls[i][4],ls[i][2][:-2],ls[i][2][-2:],ls[i][3][:-2],ls[i][3][-2:]))
else:
print("输入星座序号有误!")
sall = input('请输入星座序号(例如,5 10):')
3.1 等比数列
这里两个问题我没弄清楚:
- 输入的是数字,要用eval(input())
- 空列表,加新数据,用的是.append(不要直接赋值!);因为要打印用逗号连接,所以要str()转换为字符串
a, b, c = eval(input())
ls = []
for i in range(c):
ls.append(str(a*(b**i)))
print(",".join(ls))
3.2 斐波那契数列
a, b = 0, 1
while a<=100:
print(a, end=',')
a, b = b,a+b
3.3 格式化输出
s = input("请输入一个字符串:")
print("{:=^20}".format(s))
3.4 turtle 菱形
import turtle
turtle.right(-30)
turtle.fd(200)
turtle.right(60)
turtle.fd(200)
turtle.right(120)
turtle.fd(200)
turtle.right(60)
turtle.fd(200)
turtle.right(120)
3.5 就业人数统计
#从键盘上获取字符串,按回车键结束输入。形如:计算机 金融 计算机 建筑 土木 土木 计算机
names = input("请输入各个同学行业名称,行业名称之间用英文空格间隔(回车结束输入):")
#str.split()函数可分割从键盘上获取的字符串,返回一个列表,默认缺省分隔符为英文空格。
'''
| split(self, /, sep=None, maxsplit=-1)
| Return a list of the words in the string, using sep as the delimiter string.
|
| sep
| The delimiter according which to split the string.
| None (the default value) means split according to any whitespace,
| and discard empty strings from the result.
| maxsplit
| Maximum number of splits to do.
| -1 (the default value) means no limit.
'''
t = names.split()
d = {} #定义一个字典
for c in range(len(t)): #对列表t中每一个元素统计出现次数
d[t[c]] = d.get(t[c],0)+1 #要掌握字典get方法的具体使用,详见代码后面。
ls = list(d.items()) #将字典的items()转换为列表,形如[("计算机",3),...]
ls.sort(key=lambda x:x[1], reverse=True) # 按照数量排序
for k in range(len(ls)): #输出排序后的统计结果
zy,num = ls[k]
#例如:ls[0]=("计算机",3),执行完该语句后,zy="计算机",num = 3
print("{}:{}".format(zy,num))#按照格式输出结果
3.6 论语
write: 换行符 \n 可以在{},也可以在format()
fi = open("论语.txt", "r")
fo = open("论语-原文.txt", "w")
a=0
for line in fi:
if a==1 and line.count("【注释】")==0 and line.count("【原文】")==0:
line = line.strip(" \n")
if line.strip():#判断line是否为空串
fo.write('{}\n'.format(line))
if line.count("【原文】")>0:
a=1
if line.count("【注释】")>0:
a=0
fi.close()
fo.close()
3.7 论语 去掉每行文字中所有小括号及内部数字
for line in fi 和for line in fi.readlines() 都可以
去掉用.replace("("+"str(k)"+")")
fi = open("论语-原文.txt",'r')
fo = open("论语-提纯原文.txt",'w')
for line in fi:
for k in range(100):
line=line.replace('(' + str(k) + ')', '')
fo.write(line)
fi.close()
fo.close()
4.1
这题也有几个注意事项,报错了才知道:
- 字符串要变成数字才能索引
- 位置和数字可以共用同一个变量
- n.replace 只是暂时变换,真变换还得赋值
n = input()
s = "〇一二三四五六七八九"
for c in "0123456789":
n = n.replace(c, s[int(c)])
print(n)
4.2
#使用with语句打开文件,处理结束后,不需要使用close()语句关闭文件
with open("data.txt","r",encoding="utf-8") as fi:
for line in fi.readlines(): #遍历每一行,例如line内容为:"李启睿,110,115,119\n"
line = line.split(",") #用","分割,例如line由字符串变成了列表:["李启睿","110","115","119"]
print(eval(line[1])+eval(line[2])+eval(line[3])) #输出110+115+119表达式的结果
4.3 分词
import jieba
s ='''人工智能是包括十分广泛的科学,
它由不同的领域组成,如机器学习,计算机视觉等等,
总的说来,人工智能研究的一个主要目标是使机器能够胜任
一些通常需要人类智能才能完成的复杂工作。但不同的时代、
不同的人对这种“复杂工作”的理解是不同的。'''
ls = jieba.lcut(s)
print(ls)
4.4 三角形
import turtle as t
for i in range(3):
t.seth(i*120)
t.fd(200)
4.5 向量积(精品)
ls = [111, 222, 333, 444, 555, 666, 777, 888, 999]
lt = [999, 777, 555, 333, 111, 888, 666, 444, 222]
s = 0
for i in range(len(ls)):
s += ls[i]*lt[i] #对应i位置的元素相乘后累加
print(s)
4.5
data = input() # 输入“姓名 年龄 性别”
s = 0
n = 0
i = 0
while data:
i = i+1
ls = data.split()
s = s+int(ls[1])
if ls[2] == '男':
n = n+1
data = input()
s = s/i
print("平均年龄是{:.2f} 男性人数是{}".format(s, n))
4.6 MOOC名单
fi = open("data.txt","r")
f = open("univ.txt","w")
for line in fi:
if "alt" in line:
dx = line.split("alt=")[-1].split('"')[1]
f.write("{}\n".format(dx))
f.close()
fi.close()
4.7 星座
f = open("PY301-SunSign.csv", "r", encoding="utf-8") #正式考试可以不用指定编码,用系统默认。
ls = []
for line in f:
ls.append(line.strip('\n').split(','))
f.close()
while True:
x = input("请输入星座序号(例如,5):")
num = x.split()
for i in num:
for row in ls:
if row[0] == i:
if len(row[2]) == 3:
m1 = row[2][0]
d1 = row[2][1:3]
else:
m1 = row[2][0:2]
d1 = row[2][2:4]
if len(row[3]) == 3:
m2 = row[3][0]
d2 = row[3][1:3]
else:
m2 = row[3][0:2]
d2 = row[3][2:4]
print("{}({})的生日是{}月{}日至{}月{}日之间".format(row[1], row[4], m1, d1, m2, d2))
4.8 星座
f = open("PY301-SunSign.csv", 'r', encoding="utf-8") #正式考试可以不用指定编码,用系统默认。
ls = []
for line in f:
ls.append(line.strip(' \n').split(','))
f.close()
while True:
x = input("请输入星座序号(例如,5):")
num = x.strip(' \n').split()
for i in num:
if 0 < int(i) < len(ls): # 文件中有标题行,所以ls中多一行
for row in ls:
if row[0] == i:
m1 = row[2][0] if len(row[2]) == 3 else row[2][0:2]
d1 = row[2][1:3] if len(row[2]) == 3 else row[2][2:4]
m2 = row[3][0] if len(row[2]) == 3 else row[3][0:2]
d2 = row[3][1:3] if len(row[2]) == 3 else row[3][2:4]
print("{}({})的生日是{}月{}日至{}月{}日之间".format(row[1], row[4], m1, d1, m2, d2))
else:
print("输入星座序号有误!")
4.7 (精品)
n = 0 #记录大学数量的计数器n
m = 0 #记录学院数量的计数器m
f = open("univ.txt", "r") #以读的方式打开文件univ.txt
lines = f.readlines() #返回一个列表,列表中每一个元素对于文件中每一行
f.close()
for line in lines: #遍历列表中每一个元素
line = line.replace("\n","") #去除元素中的换行符
if '大学生' in line: #如果列表元素中包含"大学生"字符串,不做计数
continue
elif '学院' in line and '大学' in line: #形如中国科学院大学、南京理工大学紫金学院的计数处理
if line[-2:] == '学院': #例如:南京大学金陵学院,归属于学院,不归属于大学;
m += 1
elif line[-2:] == '大学': #例如:中国科学院大学,不归属于学院,归属于大学;
n += 1
print('{}'.format(line))
elif '学院' in line: #如果列表元素中包含"学院"字符串,则默认计数为学院+1
print('{}'.format(line)) #例如:江苏理工学院,归属于学院
m += 1
elif '大学' in line: #基于列表元素中不包含"学院"字符串,而包含"大学"字符串
print('{}'.format(line)) #计数为大学+1,例如南京大学
n += 1
print("包含大学的名称数量是{}".format(n)) #输出大学计数
print("包含学院的名称数量是{}".format(m)) #输出学院计数
经典 05
5.1
千分号是 ,
n = eval(input("请输入正整数:"))
print("{:->20,}".format(n))
5.2
import jieba
s = input("请输入一个字符串:")
n = len(s)
m = len(jieba.lcut(s))
print("中文字符数为{},中文词语数为{}。".format(n, m))
5.3
import jieba
txt = input("请输入一段中文文本:")
ls=jieba.lcut(txt)
print("{:.1f}".format(len(txt)/len(ls)))
5.4
import turtle
for i in range(4):
turtle.fd(100)
turtle.fd(-100)
turtle.seth((i+1)*90)
5.5
while True:
s = input("请输入不带数字的文本:")
i = 0
for p in s:
if "0" <= p <= "9":
i = i+1
if i == 0:
break
print(len(s))
5.6 三国分词
import jieba
f = open("data.txt", "r", encoding="utf-8") #正式考试可以不用指定编码,用系统默认。
text = f.read()
f.close()
ls = jieba.lcut(text)
f = open("out.txt", "w", encoding="utf-8")
for i in ls:
if i not in ["\n"]:
f.write("{}\n".format(i))
f.close()
5.7 三国曹操
f = open('out.txt', 'r', encoding="utf-8") # 以读的方式打开文件
words = f.readlines()
f.close()
D = {}
for w in words: # 词频统计
D[w[:-1]] = D.get(w[:-1], 0) + 1
print("曹操出现次数为:{} ".format(D["曹操"]))
5.6(精品题)
这题怪有趣的,不是输出小数,而是转进制;
题目里面小问题挺多,例如转译" \ "
数字转进制需要eval()
进制不需要 . , x和X的区别是,x转小写,X转大写
s = input()
print("{:\"^30x}".format(eval(s)))
历年经典 06
6.1
注意random.randint 需要前缀。以及randint(a,b) 是 [ ] 区间
import random
random.seed(100) # 此处可多行
s = 0 #
for i in range(3):
n=random.randint(1,9)
s=s+n**3# 此处可多行
print(s)
6.2 pow() 函数;.split(sep)函数
.split() 默认分割的就是空格,所以不用写.split(" ")
ntxt = input("请输入4个数字(空格分隔):")
nls=ntxt.split()
x0 = eval(nls[0])
y0 = eval(nls[1])
x1 = eval(nls[2])
y1 = eval(nls[3])
r = pow(pow(x1-x0, 2) + pow(y1-y0, 2), 0.5)
print("{:.2f}".format(r))
6.3
因为a列表里只有数字,b列表里已经被eval()转换成数字,所以不是字符串相加,而是数字相加,不用再次转换了
a = [3,6,9]
b = eval(input()) #例如:[1,2,3]
c = []
for i in range(3):
c.append(a[i]+b[i])
print(c)
6.4 三角形
import turtle as t
for i in range(3):
t.seth(i*120)
t.fd(200)
6.5 小明考试
data = input()
d = {}
while data:
t = data.split()
d[t[0]] = int(t[1])
data = input()
ls = list(d.items())
ls.sort(key=lambda x: x[1], reverse=True)
s1, g1 = ls[0]
s2, g2 = ls[len(ls) - 1]
sum = 0
for i in d.values():
sum = sum + int(i)
avg = sum/len(ls)
print("最高分课程是{}{}, 最低分课程是{}{}, 平均分是{:.2f}".format(s1, g1, s2, g2, avg))
6.6 分词
import jieba
f = open('data.txt', 'r', encoding="utf-8")
lines = f.readlines()
f.close()
D = []
for line in lines:
wordList = jieba.lcut(line) # 用结巴分词,对每行内容进行分词
for word in wordList:
if len(word) < 3: # 判断词长度,要大于等于3个长度
continue
else:
if word not in D:
D.append(word)
f = open('out1.txt', 'w', encoding="utf-8")
f.writelines('\n'.join(D))
f.close()
6.7 分词
import jieba
f = open("data.txt", "r", encoding="utf-8")
lines = f.readlines()
f.close()
d = {}
for line in lines:
wordList = jieba.lcut(line) # 用结巴分词,对每行内容进行分词
for word in wordList:
if len(word) < 3:
continue
else:
d[word] = d.get(word, 0) + 1
ls = list(d.items())
ls.sort(key=lambda x: x[1], reverse=True) # 按照词频由高到低排序
f = open('out2.txt', 'w', encoding="utf-8")
for i in range(len(ls)):
f.write('{}:{}\n'.format(ls[i][0], ls[i][1]))
f.close()
历年经典 07
7.1 随机数平方和
import random
random.seed(0)
s = 0
for i in range(5):
n = random.randint(1,97) # 产生随机数
s = s+n**2
print(s)
7.2
n = eval(input("请输入数量:"))
if n>0 and n<=1:
cost=n*160
elif n<=4:
cost=n*160*0.9
elif n<=9:
cost=n*160*0.8
else:
cost=n*160*0.7
cost=int(cost)
print("总额为:",cost)
7.3
n = eval(input("请输入一个数字:"))
print("{:+^11}".format(chr(n-1)+chr(n)+chr(n+1)))
7.4 八边形
import turtle
turtle.pensize(2)
d = 0
for i in range(1,9):
turtle.fd(100)
d += 45
turtle.seth(d)
7.5 有效票数(len(.split())=1)
f = open("vote.txt",encoding="utf-8")
names = f.readlines()
f.close()
n = 0
for name in names:
num = len(name.split())
if num == 1:
n += 1
print("有效票{}张".format(n))
7.6 评奖学金1
f = open("score.txt", "r", encoding="utf-8")#正式考试可以不用指定编码,用系统默认。
D = [] # 单个学生的数据
L = [] # 所有学生原始成绩和总成绩
# 读取学生单科成绩并计算总成绩
for line in f.readlines():
D = line.split()
s = 0 # 每个学生的总成绩初始值
for i in range(10):
s += int(D[i + 2]) # 各科成绩累加求和,+2是因为前两个元素是学号和姓名
D.append(s)
L.append(D)
f.close()
L.sort(key=lambda x: x[-1], reverse=True) # 按学生总成绩从大到小排序
f = open('candidate0.txt', 'w', encoding="utf-8")
for i in range(10):
f.write(' '.join(L[i][:-1]) + '\n')
f.close()
7.7 评奖学金2
f = open("score.txt", "r", encoding="utf-8")
D = [] # 单个学生的数据
L = [] # 所有学生原始成绩和总成绩
# 读取学生单科成绩并计算总成绩
for line in f.readlines():
D = line.split()
s = 0 # 每个学生的总成绩初始值
for i in range(10):
s += int(D[i + 2]) # 各科成绩累加求和,+2是因为前两个元素是学号和姓名
D.append(s)
L.append(D)
f.close()
L.sort(key=lambda x: x[-1], reverse=True) # 按学生总成绩从大到小排序
f = open('candidate0.txt', 'w', encoding="utf-8")
for i in range(10): # 取前十个学生数据
for j in range(len(L[i]) - 1): # 一个学生的各项数据
f.write('{} '.format(L[i][j])) # 文件中写入各项数据,用空格隔开
f.write('\n') # 换行
f.close()
历年经典 08
8.1 insert的用法:列表.insert(位置,内容)
a = [3,6,9]
b = eval(input())
j=1
for i in range(len(a)):
b.insert(j,a[i])
j+= 2
print(b)
8.2 格式化输出数字
s = input()
print("{:=>25,}".format(eval(s)))
8.3 等差序列
注意:数字处理必须加eval
a, b, c = eval(input())
ls = []
for i in range(c):
ls.append(a+b*i)
print(ls)
8.4 十二边形
import turtle
turtle.pensize(2)
d=0
for i in range(1, 13):
turtle.fd(40)
d += 30
turtle.seth(d)
8.5 向量积
ls = [111, 222, 333, 444, 555, 666, 777, 888, 999]
lt = [999, 777, 555, 333, 111, 888, 666, 444, 222]
s = 0
for i in range(len(ls)):
s+=ls[i]*lt[i]
print(s)
8.6 大学慕课1
f = open("data.txt", "r", encoding="utf-8") #正式考试可以不用指定编码,用系统默认。
lines = f.readlines()
f.close()
f = open("univ.txt", "w", encoding="utf-8")
for line in lines:
if 'alt' in line: # 判断是否有alt,若有则用'alt'分割,分割后再用'"'分割
dx = line.split('alt=')[-1].split('"')[1]
f.write('{}\n'.format(dx))
f.close()
8.7 大学慕课2
n = 0 # 记录大学数量的计数器n
m = 0 # 记录学院数量的计数器m
f = open("univ.txt", "r", encoding="utf-8") # 以读的方式打开文件univ.txt
lines = f.readlines() # 返回一个列表,列表中每一个元素对于文件中每一行
f.close()
for line in lines: # 遍历列表中每一个元素
line = line.replace("\n", "") # 去除元素中的换行符
if '大学生' in line: # 如果列表元素中包含"大学生"字符串,不做计数
continue
elif '大学' in line: # 基于列表元素中不包含"学院"字符串,而包含"大学"字符串。
# 同时有大学和学院做大学处理,例如 中国社会科学院大学 (考点)
print('{}'.format(line)) # 计数为大学+1,例如南京大学
n += 1
elif '学院' in line: # 如果列表元素中包含"学院"字符串,则默认计数为学院+1
print('{}'.format(line)) # 例如:江苏理工学院,归属于学院
m += 1
print("包含大学的名称数量是{}".format(n)) # 输出大学计数
print("包含学院的名称数量是{}".format(m)) # 输出学院计数
历年经典 09
9.1
注意不换行需要end=''
num = input().split(',')
for i in num:
print('{:>10}'.format(i),end = "")
9.2 指数增长
scale = 0.0001 # 成就值增量
def calv(base, day):
val = base * pow((1+scale),day*8)
return val
print('5年后的成就值是{}'.format(int(calv(1, 5*365))))
year = 1
while calv(1, year*365) < 100:
year += 1
print('{}年后成就值是100'.format(year))
9.3 正整数判断
注意 == 是等于, = 是赋值
while True 搭配break ,不断循环,除非打断
如果输入的数字能比较,如负整数,执行else;如果输入的是其他字符,错误,就进入except。
while True:
try:
a = eval(input('请输入一个正整数: '))
if a > 0 and int(a)==a:
print(a)
break
else:
print("请输入正整数")
except:
print("请输入正整数")
9.4 条形图
seth() 角度和数学完全一致,0度为东方,180为西方,90度为北。
turtle太多的时候可以 as t
画图要定坐标,先定下来轴长度,原点坐标。
注意笔的penup() 与pendown()
去某个位置的goto(,)
颜色 pencolor
宽度 pensize
import turtle as t #更简洁地调用turtle库
ls = [69, 292, 33, 131, 61, 254]
X_len = 400
Y_len = 300
x0 = -200
y0 = -100
t.penup()
t.goto(x0, y0)
t.pendown()
t.fd(X_len)
t.fd(-X_len)
t.seth(90) #设置笔的起始角度
t.fd(Y_len)
t.pencolor('red')
t.pensize(5)
for i in range(len(ls)):
t.penup() #提起画笔
t.goto(x0 + (i+1)*50, y0) #移到绝对坐标处,这里x坐标动,y坐标不动
t.seth(90)
t.pendown() #放下画笔
t.fd(ls[i]) #表示直线爬行的距离
t.done()
9.5 字典字符查找
字典中的列表类型,如何变数字类型?
要判断字典中是否有某个键,直接写 if xx in<字典名>:
提取字典某个值,两个方法:(1) dict[],(2)dict.get(键,找不到则返回)。1容易崩溃,2有预防措施。
import random
random.seed(2)
pdict= {'Alice':['123456789'],
'Bob':['234567891'],
'Lily':['345678912'],
'Jane':['456789123']}
name = input('请输入一个人名:')
解法1:
if name in list(pdict.keys()):
print(name,''.join(pdict[name]),random.randint(1000,9999))
else:
print("对不起,您输入的用户信息不存在。")
解法2
if name in pdict:
print("{} {} {}".format(name,pdict.get(name)[0],random.randint(1000,9999)))
else:
print("对不起,您输入的用户信息不存在。")
9.6
import jieba # 导入Python第三方库 jieba 库
def getwords(year, fname):
""" 定义获取文本函数
:param year: 年份
:param fname: 文本名称
:return: 分词结果
"""
lstr = ''
with open(fname, 'r', encoding="utf-8") as f: # with 语句打开文件,好处是读取文件后自动关闭,不需要手动关闭。正式考试可以不用指定编码,用系统默认。
for line in f.readlines(): # 以列表方式读取文本
lstr += line.strip() # 移除字符串头尾的空字符串,并合并到 lstr 变量中
ls = jieba.lcut(lstr) # 使用jieba.lcut方法分词,并返回列表
words = {} # 创建字典
for w in ls: # 遍历列表
if len(w) > 1: # 如果字符长度大于1则添加到字典中
words[w] = words.get(w, 0) + 1 # 固定语句统计数量
# 根据字典直排序,固定语法
ws = list(words.items())
ws.sort(key=lambda x: x[1], reverse=True)
# 输出排序内容
tpcs = {}
print('{}'.format(year), end='')
for i in range(9): #
print("{}:{}".format(ws[i][0], ws[i][1]), end=',')
tpcs[ws[i][0]] = ws[i][1]
i += 1
print("{}:{}".format(ws[i][0], ws[i][1]))
tpcs[ws[i][0]] = ws[i][1]
return tpcs
tpcs1 = getwords('2019:', '政府工作报告2019.txt')
tpcs2 = getwords('2018:', '政府工作报告2018.txt')
9.7
# 以下代码仅供参考。
# 求2019中的10个主题词,存于da
import jieba
def getwords(fname):
lstr = ''
with open(fname,'r') as f:
for line in f.readlines():
lstr += line.strip()
ls = jieba.lcut(lstr)
words = {}
for w in ls:
if len(w)>1:
words[w] = words.get(w,0)+1
ws = list(words.items())
ws.sort(key = lambda x:x[1],reverse = True)
tpcs = {}
for i in range(10):
tpcs[ws[i][0]] = ws[i][1]
return tpcs
tpcs1 = getwords('政府工作报告2019.txt')
tpcs2 = getwords('政府工作报告2018.txt')
comm = {}
t2019 = {}
for tp in tpcs1:
if tp in tpcs2:
comm[tp] = tpcs1[tp]
tpcs2.pop(tp)
else:
t2019[tp] = tpcs1[tp]
print('共有词语:', end='')
print(','.join(list(comm.keys())))
print('2019特有:', end='')
print(','.join(list(t2019.keys())))
print('2018特有:', end='')
print(','.join(list(tpcs2.keys())))
历年经典 10
10.1 格式化输出,注意对齐,输出字符的位置
n = input('请输入一个正整数:') #请输入一个正整数:
for i in range(int(n)):
print('{:0>2} {}'.format(i+1,">"*(i+1) ))
10.2 判断数字和字母
if i.numeric(): /两者是等价的/ if i.numeric() == True
if i.isalpha():
ns = input("请输入一串数据:")
dnum,dchr = 0,0 #双变量赋值方式
for i in ns:
if i.isnumeric(): #如果是数字字符
dnum += 1
elif i.isalpha():
dchr += 1
else:
pass #空语句,为了保持程序结构的完整性,用于占位
print('数字个数:{},字母个数:{}'.format(dnum,dchr))
10.3 格式化输出
std = [['张三',90,87,95],['李四',83,80,87],['王五',73,57,55]]
modl = "亲爱的{}, 你的考试成绩是: 英语{}, 数学{}, Python语言{}, 总成绩{}.特此通知."
for st in std:
cnt = 0
for i in range(1,4):
cnt += st[i]
print(modl.format(st[0],st[1],st[2],st[3],cnt))
10.4
注意事项:goto() 前需要 penup(),然后pendown()
.choice() 可以选择列表中的元素
import turtle as t # 对turtle库中函数调用采用更简洁的形式
import random as r
color = ['red', 'orange', 'blue', 'green', 'purple']
r.seed(1)
for i in range(5):
rad = r.randint(20, 50) # 在[20,50]之间生成一个半径值
x0 = r.randint(-100, 100)
y0 = r.randint(-100, 100)
t.color(r.choice(color))
t.penup() # 提起画笔
t.goto(x0, y0) # 移到绝对坐标处
t.pendown() # 放下画笔
t.circle(rad)
t.done()
10.5 一维列表
img = [0.69,0.292,0.33,0.131,0.61,0.254]
filter = [0.1, 0.8, 0.1]
res = []
for i in range(len(img) - 2):
k = 0 # 有多个和,所以每次赋初始值0
for j in range(3): # 求3次累计和
k += filter[j] * img[i + j] # 求3次累计和
print('k={:.3f} ,filter[{}]={:.3f},img[{}+{}]={:.3f}'.format(k, j, filter[j], i, j, img[i + j]))
res.append(k)
for r in res:
print('{:.3f}'.format(r), end=' ')
10.6 工业规划
f = open("data.txt", "r", encoding='UTF-8') # 文件是utf-8编码
line = f.read()
f.close()
# 键盘上所有中文标点符号,包括空格和换行\n符号
for i in [",", "。", "“", "”", ",", "(", ")", "【", "】", "{", "}", "《", "》", "!", ":", "、", "?", "……", ";", "—", "\n"," "]:
line = line.replace(i, "")
f = open("clean.txt", "w", encoding='UTF-8')
f.write(line)
f.close()
键盘上所有中文标点符号,包括空格和换行\n符号,使用中文shift上档键添加,共22个。
",", "。", "“", "”", ",", "(", ")", "【", "】", "{", "}", "《", "》", "!", ":", "、", "?", "……", ";", "—", "\n"," "
…… 省略号中文状态下 (shift+6)
— 破折号中文状态下 (shift+ -)
逗号句号分为,中文全角,和半角。
笨办法,打开文档看一下还有没有标点符号,一看有“破折号”冒号, 括号等,逐一加上就可以了。(如下图)
4.0 中的点,5% 的百分号,是数学符号,不清除,其他符号用文本搜索功能检查一下即可。
10.7 工业规划
import jieba
fa=open("clean.txt","r",encoding='UTF-8')
txt=fa.read()
fa.close()
words=jieba.lcut(txt)
d = {}
for word in words:
if len(word)<3:
continue
else:
d[word]=d.get(word,0)+1
lt = list(d.items())
lt.sort(key = lambda x:x[1],reverse = True)
for i in range(10):
word,count=lt[i]
if i<9:
print("{}:{}".format(word,count),end=",")
else:
print("{}:{}".format(word,count))
历年经典11
11.1 求和
s = input("请输入一个正整数: ")
cs=0 #求和初始值
for c in s:
cs += int(c) #字符转整型
print('{:=^25}'.format(cs))
11.2
s = input("请输入中文和字母的组合: ")
count=0 #求和初始值
for c in s:
if u'\u4e00' <= c <= u'\u9fa5':
count += 1
print(count)
11.3
s = input("请输入一组数据: ")
ls = s.split(",")
lt = []
for i in ls:
lt.append(eval(i))
print(max(lt))
11.4 绘制雪花
import turtle as t
import random as r
r.seed(1)
t.pensize(2)
t.pencolor('red') #设置笔的颜色
angles = 6
points= [[0,0],[50,40],[70,80],[-40,30]]
for i in range(len(points)):
x0,y0 = points[i]
t.penup() #提起画笔,与pendown配对使用
t.goto(x0,y0) #移到绝对坐标处
t.pendown() #放下画笔
length = r.randint(6, 16)
for j in range(angles):
t.forward(length) #沿着当前方向前面指定距离
t.backward(length) #沿着当前相反方向前进指定距离
t.right(360 / angles)
t.done()
11.5 全球大学排名
f = open('data.txt', 'r') # 读取文本
unis = {"美国": [], "英国": [], "瑞士": [], "新加坡": [], "中国": []} # 创建字典
for line in f: # 遍历文本
if line == "\n": # 如果文本是空行就跳过
continue
else:
text = line.split(",") # 用逗号分割文本
text[2] = text[2].replace("\n", "") # 替换国家文本尾部换行符号
unis[text[2]].append(text[1]) # 将学校名称添加到字典值的列表中
f.close()
for d in unis:
print('{:>4}: {:>4} : {}'.format(d, len(unis[d]), ",".join(unis[d]))) # 遍历字典,格式化输出内容
11.6 红楼梦
import jieba
f = "红楼梦.txt"
sf = "停用词.txt"
txt = jieba.lcut(open(f, 'r', encoding='utf-8').read()) # open函数读取红楼梦文本并分词 ,正式考试可以不用指定编码,用系统默认。
stop_words = []
with open(sf, 'r', encoding='utf-8') as f: # 读取停用词文本并分割文本后添加到stop_words列表中
for i in f.read().splitlines():
stop_words.append(i)
# 剔除停用词
txt0 = [x for x in txt if x not in stop_words]
# 统计词频
counts = {}
for word in txt0:
if len(word) == 1: # 跳过标点符号和字
continue
elif word == '凤姐儿' or word == '凤丫头':
rword = '凤姐'
elif word == '二爷' or word == '宝二爷':
rword = '宝玉'
elif word == '颦儿' or word == '林妹妹' or word == '黛玉道':
rword = '黛玉'
elif word == '宝丫头':
rword = '宝钗'
elif word == '老祖宗':
rword = '贾母'
elif word == '袭人道':
rword = '袭人'
elif word == '贾政道':
rword = '贾政'
elif word == '琏二爷':
rword = '贾琏'
else:
rword = word
counts[rword] = counts.get(rword, 0) + 1
# 固定语句将字典的值进行排序
li = list(counts.items())
li.sort(key=lambda x: x[1], reverse=True)
# 列出词频超过40的结果
with open(r'result.csv', 'a', encoding='gbk') as f:
for i in li:
key, value = i
if value < 40:
break
f.write(key + ',' + str(value) + '\n')
print(key + ',' + str(value))
历年经典12
12.1
s = input("请输入一个小数: ")
s = s[::-1]
cs = 0
for c in s:
if c == '.':
break
cs += eval(c)
print('{:*>10}'.format(cs))
12.2 time 库
注意:ctime() 中间的参数是浮点数!float()
字符串切片,注意[:] 不包含上闭区间!
import time
t = input("请输入一个浮点数时间信息: ")
s = time.ctime(float(t))
ls = s.split()
print(ls[3][0:2])
12.3 random.choice 随机密码
注意写出所有字母字符的方法:不用列举,而是ls.append(chr(ord('0')+i))
import random
s = input("请输入随机种子: ")
ls = []
for i in range(26): #向ls中添加26个字母
ls.append(chr(ord('a')+i))
for i in range(10): #向ls中添加10个数字
ls.append(chr(ord('0')+i))
random.seed(eval(s))
for i in range(10):
for j in range(8):
print(random.choice(ls),end='') #从ls序列中随机选择一个元素
print()
12.4 随机方块
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.pendown()
for j in range(4):
t.fd(length)
t.seth(90*(j+1))
t.done()
12.5 统计操作时间
sumtime = 0
percls = []
ts = {}
with open('out.txt', 'r') as f:
for line in f:
percls.append(line.strip('\n').split(","))
n=[x[1] for x in percls]
for i in range(len(n)):
sumtime+=eval(n[i])
ts={x[0]:x[2] for x in percls}
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]))
12.6
f = open("八十天环游地球.txt", encoding="utf-8") # 读取源文件
fi = open("八十天环游地球-章节.txt", "w", encoding="utf-8") # 打开新文件
for i in f: # 遍历文本
text = i.split(" ")[0] # 章节中有空格进行分割 例如:第二章 路路通认为他总算找到了理想的工作
if text[0] == "第" and text[-1] == "章": # 取出第一段文本,如果首字符是第尾字符是章,代表是章节
fi.write("{}\n".format(i.replace("\n", ""))) # 格式化保存
fi.close()
f.close()
12.7
import jieba
import re
strf = '八十天环游地球.txt'
with open(strf, encoding='utf-8') as f:
lines = f.read()
t = re.findall('(第.{1,3}章.*)', lines)
with open(strf, encoding='utf-8') as f:
lines = f.read()
s = re.sub('(第.{1,3}章.*)', '$', lines)
x = s.split('$')
x = x[1:]
# 计算词频并输出结果。
for i, j in zip(t, x):
counts = {}
txt = jieba.lcut(i+j)
for word in txt:
if len(word) >= 2:
counts[word] = counts.get(word, 0) + 1
li = list(counts.items())
li.sort(key=lambda x: x[1], reverse=True)
word_max, count_max = li[0]
chapter = re.findall('(第.*章)', i)[0]
print(chapter + ' ' + word_max + ' ' + str(count_max))
历年经典 13
13.1 格式判断
这题教我们如何判断字符串格式
ls = eval(input()) # 获取用户输入,并去除引号,ls类型为列表
s = "" # 创建字符串变量
for item in ls: # 遍历列表
if type(item) == type("str"): # 如果item变量类型等于字符串
s += item # s=s+item
print(s) # 打印输出
13.2
搞清楚 == 是判断等于,=是赋值!
input() 输入的都是字符串
eval() 去掉字符串外侧的引号,就变成了数字啦,例如eval(input())
import random
random.seed(25)
n = random.randint(1,100)
for m in range(1,7):
x = eval(input("请输入猜测数字:"))
if x == n:
print("恭喜你,猜对了!")
break
elif x > n:
print("大了,再试试")
else:
print("小了,再试试")
if m == 6:
print("谢谢!请休息后再猜")
13.3
def func(n):
s = 0
if n % 2 == 1:
for i in range(1, n + 1, 2):
s += 1 / i
else:
for i in range(2, n + 1, 2):
s += 1 / i
return s
number = int(input())
print('{:.2f}'.format(func(number)))
13.4
注意圆心在(0,0),画圆的圆心在左(初始正东方向)半径r处,所以当半径为10时,圆心应该在(0,-10)。
from turtle import *
color = ['red', 'green', 'blue']
rs = [10, 30, 60]
for i in range(3):
penup()
goto(0, -rs[i])
pendown()
pencolor(color[i])
circle(rs[i])
done()
13.5
关注后面一半的操作:输出不带标点符号的两行文字。
先设定空字符串poetry,判定非符号,则字符串相加;判定为符号,则打印不带符号的字符串,然后清空字符串。
while套if 单分支,结合continue使用就能实现else的效果。
import jieba
text = input("请输入一段中文文本,句子之间以逗号或句号分隔:")
lst = jieba.lcut(text)
number_of_words = 0
for i in lst:
if i in ",。":
continue
number_of_words += 1
print(i, end='/')
print("\n中文词语数是:{}\n".format(number_of_words))
poetry = ''
for i in text:
if i in ',。':
print('{: ^20}'.format(poetry))
poetry = ''
continue
poetry += i
13.6
注意文件开启和关闭;注意'r' 的引号;
注意readlines是每一行作为列表的一个元素,所以for item in f.readlines: 就读取每一行的数据
注意要去掉头尾空格.strip() 再分割.split(':'),分割一次当然是变成两个
打印换行就直接用字符串连接即可
.write(s) 写的是字符串;.writelines(ls) 写的是全为字符串的列表,写进去的列表元素同在一行,例如ls=['窗前','明月','光'],写之后是 窗前明月光
f_data = open('data.txt', 'r', encoding="utf-8")
f_studs = open('studs.txt', 'w', encoding="utf-8")
student_lst = f_data.readlines()
for student in student_lst:
student = student.strip().split(':')
name = student[0]
score = student[1].split(',')[-1]
f_studs.write(name + ':' + score + '\n')
f_data.close()
f_studs.close()
13.7
既然要排序,就用到列表,先设空列表lst=[]
将组好的变量构成列表,不要想到字典去,列表可以嵌套列表的。lst.append([name,score])
.sort 作排序。注意字符串要转换成数字 eval(),以及True 才是大到小,也就是默认从小到大。
lst.sort(key = lambda x: eval(x[1]) ,reverse= True)
打印一个字符,不用循环,直接字符串索引然后穿起来 print(lst[0][0]+":"+lst[0][1])
f_data = open('data.txt', 'r', encoding="utf-8")
students = f_data.readlines()
lst = []
for student in students:
student = student.strip().split(':')
name = student[0]
score = student[1].split(',')[-1]
lst.append([name, score])
lst.sort(key=lambda x: eval(x[1]), reverse=True)
print(lst[0][0] + ':' + lst[0][1])
f_data.close()
13.8
f_data = open('data.txt', 'r', encoding="utf-8")
d = {}
students = f_data.readlines()
for student in students:
student = student.strip().split(':')
CLASS, score = student[1].split(',')
d[CLASS] = d.get(CLASS, []) + [eval(score)]
for key in d:
avg_score = sum(d[key]) / len(d[key])
print('{}:{:.2f}'.format(key, avg_score))
f_data.close()