Python第四次作业
设计题1: 设计一个本月份日历,输出格式如下:
要求: 1.初始化start_day,end_day两个日期
from datetime
import datetime
start_day=datetime(2019,4,1)
end_day=datetime(2019,4,30)
其它时间数据生成要用datetime或date模块的方法编程实现 2.不能使用calendar模块生成
from datetime import datetime start_day = datetime(2019, 4, 1) end_day = datetime(2019, 4, 30) print("\t\t2019年4月") print("星期一 星期二 星期三 星期四 星期五 星期六 星期天") day = end_day - start_day # 总天数 month = start_day.month #月份 first = start_day.weekday() # 第一天是星期几 day = day.days + 1 # 所求月份的天数 count = 0 k = 1 while k <= first: k += 1 print("\t", end="") count += 1 if (count % 7 == 0): print("\n") f = 1 while f <= day: # 判断天数 print(f, end="\t") f += 1 count += 1 if (count % 7 == 0): # 每七天换行 print("\n")
设计题2:
1.参考“三国演义”词频统计程序,实现对红楼梦出场人物的频次统计。
2.(可选)
将红楼梦出场人物的频次统计结果用词云显示。
import jieba excludes = {"一个","我们","那里","如今","说道","知道","起来","这里","出来","他们","众人", "自己","没有","听见","怎么","什么","咱们","告诉","一面","东西","平儿","袭人","回来", "只是","只见","老爷","大家","只得","丫头","这些","不敢","出去","所以","不过",} txt = open("红楼梦.txt", "r", encoding='utf-8').read() words = jieba.lcut(txt)#精确模式的分词函数,返回一个列表数据类型 #print(type(words)) #words的数据类型 counts = {} #定义一个字典 for word in words: if len(word) == 1: continue elif word == "林黛玉"or word == "颦颦"or word == "颦儿": rword = "潇湘妃子" elif word == "贾宝玉" or word == "绛洞花主"or word == "富贵闲人"or word == "怡红公子": rword = "宝二爷" elif word == "薛宝钗" or word == "宝钗"or word == "宝姐姐" or word=="薛大姑娘": rword = "蘅芜君" elif word == "贾琏" or word == "琏二爷": rword = "二爷" elif word == "王熙凤" or word == "凤姐"or word == "凤姐儿"or word == "凤哥儿"or word == "醋坛子": rword = "琏二奶奶" elif word == "秦可卿"or word == "可卿": rword = "兼美" elif word == "贾母" or word == "老太太"or word == "老祖宗"or word == "老神仙": rword = "史太君" elif word == "贾惜春" or word == "惜春": rword = "惜春" elif word == "史湘云" or word == "史大姑娘"or word == "湘云" or word=="云妹妹": rword = "枕霞旧友" elif word == "芙蓉仙子" or word == "病西施": rword = "晴雯" elif word == "探春" or word == "贾探春"or word == "三姑娘": rword = "玫瑰花" elif word == "芳 官" or word == "耶律雄奴": rword = "金星玻璃" elif word =="柳湘莲": rword ="冷二郎" else: rword = word counts[rword] = counts.get(rword,0) + 1 #词汇加入字典 for word in excludes: del(counts[word]) #从字典中删除无用词 items = list(counts.items()) #字典转换为列表 #lambda是一个隐函数,是固定写法,以下命令的意思就是按照记录的第2列排序 """x表示列表中的一个元素,x只是临时起的一个名字, 你可以使用任意的名字""" items.sort(key=lambda x:x[1], reverse=True) for i in range(20): #出现的词频统计 word, count = items[i] #将键和值分别赋予列表word和count print ("{0:<10}{1:>5}".format(word, count))#0:<10左对齐,宽度10,”>5"右对齐