从CSV格式文件中抽取数据
row_data = {}
with open('PaceData.csv') as paces:
column_headings = paces.readline().strip().split(',')
column_headings.pop(0)
for each_line in paces:
row = each_line.strip().split(',')
row_label = row.pop(0)
row_data[row_label] = row
num_cols = len(column_headings)
print(num_cols, end=' -> ')
print(column_headings)
num_2mi = len(row_data['2mi'])
print(num_2mi, end=' -> ')
print(row_data['2mi'])
num_Marathon = len(row_data['Marathon'])
print(num_Marathon, end=' -> ')
print(row_data['Marathon'])
将各个时间存储为字典
row_data = {}
with open('PaceData.csv') as paces:
column_headings = paces.readline().strip().split(',')
column_headings.pop(0)
for each_line in paces:
row = each_line.strip().split(',')
row_label = row.pop(0)
inner_dict = {}
for i in range(len(column_headings)):
inner_dict[row[i]] = column_headings[i] #将列标题与行中的时间值关联
row_data[row_label] = inner_dict #填充字典后,将其赋至“row_data”中相应行标签。
得到用户输入
input()BIF可以在屏幕上显示一个提示语,然后接收键盘输入,并把输入的内容作为一个字符串返回给代码。
distance_run = input('Enter the distance attempted: ')
recorded_time = input('Enter the recorded time: ')
predicted_distance = input('Enter the distance you want a prediction for: ')
获取输入会产生一个问题,输入的时间值在表格的两个值之间无法找到
搜索最接近的匹配
def find_closest(look_for, target_data):
def whats_the_difference(first, second): #嵌套函数
if first == second:
return(0)
elif first > second:
return(first - second)
else:
return(second - first)
max_diff = 9999999
for each_thing in target_data:
diff = whats_the_difference(each_thing, look_for)
if diff == 0:
found_it = each_thing
break
elif diff < max_diff:
max_diff = diff
found_it = each_thing
return(found_it)
时间有问题
CSV中的值都是字符串,find_closest()函数处理的是数字,导致混乱。
时间-秒转换模块
import time
def format_time(time_string): #确保所有时间都采用“HH:MM:SS"格式。
tlen = len(time_string)
if tlen < 3:
original_format = '%S'
elif tlen < 6:
original_format = '%M:%S'
else:
original_format = '%H:%M:%S'
time_string = time.strftime('%H:%M:%S', time.strptime(time_string, original_format))
return(time_string)
def time2secs(time_string): #给定一个”时间字符串“,转换为一个秒数值
time_string = format_time(time_string)
(hours, mins, secs) = time_string.split(':')
seconds = int(secs) + (int(mins)*60) + (int(hours)*60*60)
return(seconds)
def secs2time(seconds): #将一个秒数值转换为”时间字符串“
return(time.strftime('%H:%M:%S', time.gmtime(seconds)))
定义一个新函数,它取两个参数,要查找的时间和所搜索的时间列表,把最接近的时间作为一个字符串返回:
from find_it import find_closest
from tm2secs2tm import time2secs, secs2time
def find_nearest_time(look_for, target_data):
what = time2secs(look_for)
where = [time2secs(t) for t in target_data]
res = find_closest(what, where)
return(secs2time(res))
时间还有问题
导入”format_time()“函数,确保时间字符串采用HH:MM:SS格式
from find_it import find_closest
from tm2secs2tm import time2secs, secs2time, format_time
def find_nearest_time(look_for, target_data):
what = time2secs(look_for)
where = [time2secs(t) for t in target_data]
res = find_closest(what, where)
return(secs2time(res))
row_data = {}
with open('PaceData.csv') as paces:
column_headings = paces.readline().strip().split(',')
column_headings.pop(0)
for each_line in paces:
row = each_line.strip().split(',')
row_label = row.pop(0)
inner_dict = {}
for i in range(len(column_headings)):
inner_dict[format_time(row[i])] = column_headings[i]
row_data[row_label] = inner_dict
distance_run = input('Enter the distance attempted: ')
recorded_time = input('Enter the recorded time: ')
predicted_distance = input('Enter the distance you want a prediction for: ')
closest_time = find_nearest_time(format_time(recorded_time), row_data[distance_run])
closest_column_heading = row_data[distance_run][closest_time]
prediction = [k for k in row_data[predicted_distance].keys()
if row_data[predicted_distance][k] == closest_column_heading]
print('The predicted time running ' + predicted_distance + ' is: ' + prediction[0] + '.')
移植到android
设计一堆对话框
import time
import android
from find_it import find_closest
from tm2secs2tm import time2secs, secs2time, format_time #完成导入
def find_nearest_time(look_for, target_data): #包含”find_nearest()“函数
what = time2secs(look_for)
where = [time2secs(t) for t in target_data]
res = find_closest(what, where)
return(secs2time(res))
distances = [ '2mi', '5k', '5mi', '10k', '15k', '10mi', '20k', #声明常量
'13.1mi', '25k', '30k', 'Marathon' ]
hello_msg = "Welcome to the Marathon Club's App"
quit_msg = "Quitting the Marathon Club's App."
row_data = {}
with open('/sdcard/sl4a/scripts/PaceData.csv') as paces: #打开一个特定文件夹,得到并预处理CVS数据
column_headings = paces.readline().strip().split(',')
column_headings.pop(0)
for each_line in paces:
row = each_line.strip().split(',')
row_label = row.pop(0)
inner_dict = {}
for i in range(len(column_headings)):
inner_dict[format_time(row[i])] = column_headings[i]
row_data[row_label] = inner_dict
app = android.Android() #创建android应用对象,并包含你的辅助函数
def status_update(msg, how_long=2):
app.makeToast(msg)
time.sleep(how_long)
def do_dialog(title, data, func, ok='Select', notok='Quit'):
app.dialogCreateAlert(title)
func(data)
app.dialogSetPositiveButtonText(ok)
if notok:
app.dialogSetNegativeButtonText(notok)
app.dialogShow()
return(app.dialogGetResponse().result)
status_update(hello_msg)
resp = do_dialog("Pick a distance", distances, app.dialogSetSingleChoiceItems) #向用户显示用户界面,并交互处理
if resp['which'] in ('positive'):
distance_run = app.dialogGetSelectedItems().result[0]
distance_run = distances[distance_run]
recorded_time = app.dialogGetInput("Enter a " + distance_run + " time:",
"Use HH:MM:SS format:").result
closest_time = find_nearest_time(format_time(recorded_time), row_data[distance_run])
closest_column_heading = row_data[distance_run][closest_time]
resp = do_dialog("Pick a distance to predict", distances, app.dialogSetSingleChoiceItems)
if resp['which'] in ('positive'):
predicted_distance = app.dialogGetSelectedItems().result[0]
predicted_distance = distances[predicted_distance]
prediction = [k for k in row_data[predicted_distance].keys()
if row_data[predicted_distance][k] == closest_column_heading]
do_dialog('The predicted time running ' + predicted_distance + ' is: ',
prediction, app.dialogSetItems, "OK", None)
status_update(quit_msg)