用Python构建个性化智能闹钟( 二 )


因此,我们使用前面定义的helper函数来找出由文件夹获得的列表和从CSV文件获得的列表之间的任何差异 。
因此,我们可以对代码执行所需的操作,并分别使用它们各自的公式更新tune_prob_rev和tune_prob 。
# 如果存在csv文件,则从csv文件读取else:tune_df = pd.read_csv("tune_parameters.csv")tune_list_os = os.listdir(alarm_path)tune_list = list(tune_df['Tunes'])tune_diff = List_diff(tune_list_os, tune_list)tune_time = list(tune_df['Delay Times'])tune_counter = list(tune_df['Count'])tune_avg = list(tune_df['Average'])tune_prob_rev = list(tune_df['Reverse Probability'])tune_prob = list(tune_df['Probability'])if len(tune_list_os)>=len(tune_list):for i in range(0,len(tune_diff)):tune_list.Append(tune_diff[i])tune_time.append(60)tune_counter.append(1)tune_avg.append(60)tune_prob_rev.append(0.1)tune_prob.append(0.1)else:for i in range(0,len(tune_diff)):tune_diff_index = tune_list.index(tune_diff[i])tune_list.pop(tune_diff_index)tune_time.pop(tune_diff_index)tune_counter.pop(tune_diff_index)tune_avg.pop(tune_diff_index)tune_prob_rev.pop(tune_diff_index)tune_prob.pop(tune_diff_index)avg_sum = sum(tune_avg)for i in range(0,len(tune_prob_rev)):tune_prob_rev[i] = 1 - tune_avg[i]/avg_sumavg_prob = sum(tune_prob_rev)for i in range(0,len(tune_prob)):tune_prob[i] = tune_prob_rev[i]/avg_prob设置闹钟并验证时间现在,我们需要定义另一个helper函数来检查用户输入的时间是否正确 。因此,我们定义了verify_alarm函数来执行此操作 。
# 验证输入的时间是否正确 。def verify_alarm(hour,minute,seconds):if((hour>=0 and hour<=23) and (minute>=0 and minute<=59) and (seconds>=0 and seconds<=59)):return Trueelse:return False现在,我们准备好了helper函数 。所以,我们需要询问用户报警时间 。我们将使用一个循环来请求闹钟,一旦我们确认时间有效,我们就会中断 。如果无效,我们将再次询问用户,直到他输入有效时间 。
# 要求用户设置报警时间并验证是否正确 。while(True):hour = int(input("Enter the hour in 24 Hour Format (0-23):t"))minute = int(input("Enter the minutes (0-59):t"))seconds = int(input("Enter the seconds (0-59):t"))if verify_alarm(hour,minute,seconds):breakelse:print("Error: Wrong Time Entered! Please enter again!")现在,在接受用户的输入后,我们将找出当前时间,并将这两个时间转换为秒,并找出时间之间的差异 。如果差值为负,则意味着闹钟将在第二天发出 。
然后,我们将使python代码休眠这几秒钟,以便只在需要的时间发出闹铃 。
# 将报警时间转换为秒alarm_sec = hour*3600 + minute*60 + seconds# 获取当前时间并将其转换为秒curr_time = datetime.datetime.now()curr_sec = curr_time.hour*3600 + curr_time.minute*60 + curr_time.second# 计算剩余报警秒数time_diff = alarm_sec - curr_sec# 如果时差为负,则表示闹钟为第二天 。if time_diff < 0:time_diff += 86400# 显示剩余时间print("Time left for alarm is %s" % datetime.timedelta(seconds=time_diff))# 睡到闹钟响的时候time.sleep(time_diff)播放闹铃现在,我们将播放闹铃,我们需要根据概率列表随机选择闹铃 。要播放闹音,我们将使用pygame.mixer.music库 。我们将无限循环闹铃,直到用户停止 。
print("Alarm time! Wake up! Wake up!")# 根据概率选择闹铃tune_choice_np = np.random.choice(tune_list, 1, tune_prob)tune_choice = tune_choice_np[0]# 获取索引tune_index = tune_list.index(tune_choice)# 播放闹铃mixer.init()mixer.music.load(alarm_path+"/"+tune_choice)# 设置loops=-1以确保报警仅在用户停止时停止!mixer.music.play(loops=-1)# 要求用户停止闹钟input("Press ENTER to stop alarm")mixer.music.stop()计算和更新现在,我们将根据用户停止报警所需的时间更新列表的值 。
我们将找到报警与当前停止报警时间之间的时差 。我们将其转换为秒,然后相应地更新 。
# 找到停止闹钟的时间time_stop = datetime.datetime.now()stop_sec = time_stop.hour*3600 + time_stop.minute*60 + time_stop.second# 计算时间延迟time_delay = stop_sec - alarm_sec# 更新值tune_time[tune_index] += time_delaytune_counter[tune_index] += 1tune_avg[tune_index] = tune_time[tune_index] / tune_counter[tune_index]new_avg_sum = sum(tune_avg)for i in range(0,len(tune_list)):tune_prob_rev[i] = 1 - tune_avg[i] / new_avg_sumnew_avg_prob = sum(tune_prob_rev)for i in range(0,len(tune_list)):tune_prob[i] = tune_prob_rev[i] / new_avg_prob合并列表并另存为CSV文件现在,我们将所有的列表合并到一个多维列表中,然后将其转换为pandas数据帧,然后将其保存为CSV文件 。
# 创建列表tune_rec = [[[[[[]]]]]]for i in range (0,len(tune_list)):temp=[]temp.append(tune_list[i])temp.append(tune_time[i])temp.append(tune_counter[i])temp.append(tune_avg[i])temp.append(tune_prob_rev[i])temp.append(tune_prob[i])tune_rec.append(temp)tune_rec.pop(0)# 将合并列表转换为数据帧df = pd.DataFrame(tune_rec, columns=['Tunes','Delay Times','Count','Average','Reverse Probability','Probability'],dtype=float)# 将数据帧保存为csvdf.to_csv('tune_parameters.csv',index=False)


推荐阅读