第二章-python语言基础-2.7字典(理)
第1关:字典的创建和基本操作
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 6 16:36:42 2020
@author: Administrator
"""
# 创建并初始化score_dict字典
score_dict = {}
for i in range(5):
key = input()
value = input()
if value.isdigit():
value = int(value)
score_dict[key] = value
score_dict['体育'] = 90
if '化学' in score_dict:
print(score_dict['化学'])
else:
print('不存在')
if '语文' in score_dict:
score_dict['语文'] = 100
if '信息' in score_dict:
del score_dict['信息']
print(score_dict)
####### End #######
# 请按下面的注释提示添加代码,完成相应功能
#2.请在此添加代码,实现对score_dict的添加、删除、查找、修改等操作,并打印输出相应的值
###### Begin ######
####### End #######
第2关:字典的遍历
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 6 16:36:42 2020
@author: Administrator
"""
# 创建并初始化score_dict字典
score_list=['姓名','语文','英语','数学','体育','总分']
# 请按下面的注释提示添加代码,完成相应功能
#1.根据上面的列表创建score_dict字典并初始化,得到如任务描述中的字典,字典中的值从键盘输入
###### Begin ######
score_dict = {}
####### End #######
li = []
# 请按下面的注释提示添加代码,完成相应功能
#2.请在此添加代码,计算张三同学的总分,并将总分作为新的键值对加入,最后输出score_dict的所有键值对
###### Begin ######
for i in range(5):
a=input()
if a.isdigit():
a= int(a)
li.append(a)
li.append(sum(li[1:]))
#print(li)
for n in range(len(li)):
score_dict[score_list[n]] = li[n]
for i in score_dict:
print(i,score_dict[i])
####### End #######
第3关:字典和列表的嵌套
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 6 16:36:42 2020
@author: Administrator
"""
#创建空列表score_dict
score_dict={}
#每次循环生成一个键值对
for i in range(3):
#输入课程名作为字典的键
key=input()
# 创建空列表
value_list=[]
# 请按下面的注释提示添加代码,完成相应功能
#1.从键盘输入两个分数,保存到列表中
###### Begin ######
value_list.append(eval(input()))
value_list.append(eval(input()))
####### End #######
score_dict[key]=value_list
print(score_dict)
#创建空列表score_list
score_list=[]
#每次循环生成一个字典
for i in range(2):
# 创建空字典
s_dict={}
# 请按下面的注释提示添加代码,完成相应功能
#2.对从键盘输入三门课程及成绩,保存到字典中
###### Begin ######
for i in range(3):
key=input()
value = eval(input())
s_dict[key] = value
####### End #######
score_list.append(s_dict)
print(score_list)
实验十 字典
第1关:统计文档中作者作品数量
f1=open("sy9//中学诗词.txt","r",encoding='utf-8')
#代码开始
d1 = {}
for lines in f1:
line = lines.split()
if len(line) >= 2 and len(line[-1]) <= 4:
if line[-1] in d1:
d1[line[-1]] += 1
else:
d1[line[-1]] = 1
#print(d1)
lt = sorted(list(d1.items()),key=lambda x:x[1],reverse = True)
#print(lt)
#print(line.split())
#代码结束
for i in lt:
print(i[0],i[1])
f1.close()
排序的时候注意使用值排序就行了
第2关:候选人票数统计
tp=[]
x=input("")
while(x!="end"):
tp.append(x)
x=input("")
#代码开始
#print(tp)
d1 = {}
d2 = {}
for i in tp:
if i in d1:
d1[i] += 1
else:
d1[i] = 1
#print(d1)
for n,m in d1.items():
d2[m] = n
items = sorted(list(d2.items()),reverse = True)
#print(items)
#代码结束
for i in range(len(items)):
print("第{}名姓名{}票数{}".format(i+1,items[i][1],items[i][0]))
这么写也行,学会上文的排序这个就没必要了
第3关:会员会费计算第4关:职工工资计算
f1=open("sy9//会员名单.txt","r",encoding="utf8")
#代码开始
l1 = []
d1 = {}
for line in f1:
l1.append(line.split())
#print(l1)
for n in l1:
#print(n)
a = n[0].split(',')[0]
d1[a] = 0
if '黄金' in n[0]:
d1[a] += 199
if '星钻' in n[0]:
d1[a] += 399
if '大众' in n[0]:
d1[a] += 98
if '专业' in n[0]:
d1[a] += 198
#d1[n[:n.find(',')]] = 0
#print(d1)
#if n[1] == ''
for i in d1:
print(i,d1[i])
#代码结束
f1.close()
第4关:职工工资计算
zg,yfgz=[],[]
xx=input("")
while(xx!="end"):
sj=xx.split(',')
zg.append([sj[0],eval(sj[1]),sj[2],sj[3]])
xx=input("")
jt={'北京':5000,'上海':4000,'广州':3000,'销售部':2000,'经理室':3000,'财会部':1000}
for i in zg:
a,b,c,d=i[0],i[1],i[2],i[3]
y=jt.get(c,0)+jt.get(d,0)+b
yfgz.append([a,y])
yfgz.sort(key=lambda x:x[1],reverse=True)
for x in yfgz:
print("姓名"+x[0]+"工资"+str(x[1]))
第5关:文件币种兑换计算
f1=open("sy9//汇率兑换.txt","r",encoding="utf-8")
bzzd={}
for line in f1:
line=line.strip('\n')
dh=line[line.find('(')+1:line.find('(')+4]
hl=eval(line[line.find('= ')+2:line.find(' 人民币')])
bzzd[dh]=hl
while True:
x=input()
if x=='0':
break
dh=x[:3].upper()
sl=x[3:]
if dh not in bzzd.keys():
print('币种错误')
elif sl.isdigit()==False:
print('数字错误')
else:
sl=eval(sl)
hl=bzzd.get(dh,0)
e=hl*sl
print('人民币{:.2f}'.format(e))
f1.close()
第6关:饮品销售计算
f1=open("sy9//nc.csv","r",encoding="utf8")
goods={}
for line in f1.readlines():
x=line.strip().split(',')
print(f'编号{x[0]}饮品{x[1]}价格{x[2]}')
goods[x[0]]=eval(x[2])
y,je=input("请选择饮品"),0
while y!='00':
if y in goods.keys():
num=eval(input('请输入数量'))
je+=num*goods[y]
else:
print('编码错误')
y=input('请选择饮品')
print("应付{}元".format(je))
此处应有茶颜广告费
第7关:统计文件词语的词频
import jieba
jieba.setLogLevel(jieba.logging.INFO)
f1= open("sy9//宋词.txt", "r")
txt,pc=f1.read(),set()
f1.seek(0,0)
for line in f1:
if ' ' in line and ','not in line and','not in line and '。'not in line:
a,b=line.split(' ')
pc.add(a)
pc.add(b)
for ch in ',.?!,。?!':
txt=txt.replace(ch,' ')
words,counts=jieba.lcut(txt),{}
pc=pc|{'吴文英','姜夔'}
for word in words:
if len(word)>1 and word not in pc:
counts[word]=counts.get(word,0)+1
counts['东风']=counts.get('东风',0)-1
items=list(counts.items())
items.sort(key=lambda x:x[1],reverse=True)
for i in range(15):
print("{}{}".format(items[i][0],items[i][1]))
太麻烦了,而且不考
第8关:宋词文件词云图片
import jieba
import wordcloud
f1= open("sy9//宋词.txt", "r")
txt,pc=f1.read(),set()
f1.seek(0,0)
for line in f1:
if " " in line:
cp=line[:line.find(" ")]
pc.add(cp)
xm=line[line.find(" ")+1:].strip("\n")
pc.add(xm)
f1.close()
for i in pc:
txt=txt.replace(i,"")
counts,words= {},jieba.lcut(txt)
for word in words:
if len(word)>1 :
counts[word] = counts.get(word,0) + 1
w=wordcloud.WordCloud(font_path="sy9//simhei.ttf",background_color='white',max_words=300,width=1000,height=700)
w.generate_from_frequencies(counts)
w.to_file("sy9//pict//sc1.png")
总结:
抄就完了,这一块偏离主线了。