Python案例练习:字典专题(分析文章的文字与次数、设计星座字典、凯撒密码、摩尔斯密码)
传统方式分析文章的文字与次数
composition = '''This is my family. We have a father, a mother and two brothers.
My father is a doctor. He works in a hospital. My mother is a teacher.
She teaches English in a school. My older brother is a student. He studies in a university.
My younger brother is a child.He is only five years old.
We often go to the park together on Sundays.My best friend is John.
He is very tall and has short hair. He always wears a smile on his face.
He likes playing basketball and listening to music.
We often study together and help each other with our homework.
He is very kind and always ready to help others. I am very lucky to have him as my friend.'''print('原始作文:', composition)# 小写作文
composition = composition.lower()
print('小写作文:',composition)
for char in composition:if char in ".?,":composition = composition.replace(char,'')
print('不再有标点符号的作文:',composition)# 做切割,以空格为切割符,实现字符串的切割
composition = composition.split()# 统计列表中每一个单词出现的次数
wordDic = {}
for word in composition:if word not in wordDic:wordDic[word] = 1else:wordDic[word] += 1print(wordDic)
执行结果
设计星座字典
这个程序会要求输入星座,如果所输入的星座正确,则输出此星座的时间区间和本月运势,如果所输入的星座错误,则输出“星座输入错误”
#这个程序会要求输入星座,如果所输入的星座正确,则输出此星座的时间区间和本月运势,如果所输入的星座错误,则输出“星座输入错误”season = {'水瓶座':'1月20日 - 2月18日,需警惕小人','双鱼座':'2月19日 - 3月20日,凌乱中找立足','白羊座':'3月21日 - 4月19日,运势好','金牛座':'4月20日 - 5月20日,烂桃花','双子座':'5月21日 - 6月21日,有财运','巨蟹座':'6月22日 - 7月22日,有贵人','狮子座':'7月23日 - 8月24日,防漏财','处女座':'8月25日 - 9月23日,普通通','天秤座':'9月24日 - 10月23日,小挫折','天蝎座':'10月24日 - 11月24日,大机会','射手座':'11月25日 - 12月24日,注意财产','摩羯座':'12月25日 - 1月19日,有意外惊喜'}# 提示用户输入对应星座
word = input('请输入查询的星座')if word in season.keys():print(season[word])
else:print("输入的星座有误")
执行结果1
执行结果2:
其中:
if word in season.keys():
可以替换为
if word in season:
因为key是唯一的,可以简写
文件加密:凯撒密码实战
abc = 'abcdefghrgklmnopqrstuvwxyz'sub_text = abc[3:] +abc[:3]encryption_dict = dict(zip(sub_text, abc))
print(encryption_dict)# 密文列表
cipher = []message = input('请输入原字符串: ')
for letter in message:value = encryption_dict[letter]cipher.append(value)cipher_text = ''.join(cipher)
print(cipher_text)
执行结果
摩尔斯密码
摩尔斯密码是美国人艾尔菲德维尔与布利斯摩尔斯在1836年发明的,这是一种时通时断的信号代码,可以使用无线电型号传递,通过不同的排列组合表达不同的英文字母、数字和标点符号
代码
# 摩斯密码
morse_code = {'A':'.-', 'B':'-...', 'C':'-.-.', 'D':'-..', 'E':'.', 'F':'..-.','G':'--.', 'H':'....', 'I':'..', 'J':'.---', 'K':'-.-', 'L':'.-..','M':'--', 'N':'-.', 'O':'---', 'P':'.--.', 'Q':'--.-', 'R':'.-.','S':'...', 'T':'-', 'U':'..-', 'V':'...-', 'W':'.--', 'X':'-..-','Y':'-.--', 'Z':'--..'}message = input('请输入大写英文字符: ')for letter in message:cipher = morse_code[letter]print(cipher)
执行结果