2015-09-06 33 views
0

我有一个计算项目,用于读取文本文档的学校以及在每个强度上花费最多时间练习的人。当它运行时变量不会改变,它仍然显示最高分是0,如果有人能帮助告诉我我出错的地方会很棒,变量将不会从python中的文本文档中更改

谢谢!

文本文件看起来是这样的:

NeQua,High,Running,5,Swimming,40,Aerobics,40,Football,20,Tennis,10 
ImKol,Moderate,Walking,40,Hiking,0,Cleaning,40,Skateboarding,30,Basketball,20 
YoTri,Moderate,Walking,20,Hiking,30,Cleaning,40,Skateboarding,20,Basketball,40 
RoDen,High,Running,20,Swimming,20,Aerobics,40,Football,30,Tennis,50 

etc. 

moderate_top_player = "" 
high_top_player = "" 
moderate_top_score = 0 
high_top_score = 0 


# open file, with will automatically close it for you 
with open("text_documents/clientRecords.txt") as f: 
    for line in f: 
     ID,intensity,activity_1,time_1,activity_2,time_2,activity_3,time_3,activity_4,time_4,activity_5,time_5 = line.split(",") 
     client_score = int(time_1) + int(time_2) + int(time_3) + int(time_4) + int(time_5) 
     if intensity == "high" and client_score > high_top_score: 
      high_top_score = int(client_score) 
      high_top_player = str(ID) 

     elif intensity == "moderate" and client_score > moderate_top_score: 
      moderate_top_score = client_score 
      moderate_top_player = ID 

打印(moderate_top_player, “工作”,moderate_top_score, “关于中等强度分钟”) 打印(high_top_player, “工作”, high_top_score,“高强度分钟”)

+0

这条线是什么? ID,强度,activity_1,time_1,activity_2,time_2,activity_3,time_3,activity_4,time_4,activity_5,time_5 = line.split(“,”) client_score = int(time_1)+ int(time_2)+ int(time_3)+ int(time_4)+ int(time_5) – Richard

+0

是'ID'总是一个字符串还是总是一个int?代码似乎并不一致 – Pynchia

回答

3

我冒昧地重命名了一些变量,并使用Python标准中的csv模块库来读取文本文件,而不是根据逗号手动分割线。

这就是说,问题是非常简单的解决。您的数据集clientRecords.txt使用大写字符串intensity(例如HighModerate),但在您的条件下,您正在比较小写字符串。 High == high返回False,因此ifelif块的主体永远不会执行。

import csv 

moderate_top_player = "" 
high_top_player = "" 
moderate_top_score = 0 
high_top_score = 0 

with open('text_documents/clientRecords.txt', 'rb') as f: 
    reader = csv.reader(f) 
    for row in reader: 
     player_id, intensity, a1, t1, a2, t2, a3, t3, a4, t4, a5, t5 = row 
     client_score = int(t1) + int(t2) + int(t3) + int(t4) + int(t5) 
     intensity = intensity.lower() 
     if intensity == 'high' and client_score > high_top_score: 
      high_top_score = client_score 
      high_top_player = player_id 
     elif intensity == 'moderate' and client_score > moderate_top_score: 
      moderate_top_score = client_score 
      moderate_top_player = player_id 

print moderate_top_player, moderate_top_score 
print high_top_player, high_top_score 

的重要线路:

intensity = intensity.lower() 

另一方面,不是将读入intensity降低的情况下,你可以改变你的if语句来测试针对High,而不是highModerate代替moderate 。无论哪种方式都可以。

+0

谢谢,那是一个很愚蠢的错误!我觉得自己没有发现它是一个白痴! – iddyman

+0

@iddyman不要担心,在编写程序时这是很常见的 - 即使你已经做了很长时间了。 – chucksmash

相关问题