2013-12-07 120 views
0

我是Python的新手,一般編程需要一點幫助(部分完成)的功能。它用一串逗號分隔的數據(年齡,薪水,教育等等)調用一個文本文件。不過,我從一開始就遇到了一個問題。我不知道如何返回結果。如何打印此功能的結果

我的目標是爲每個類別創建字典並對每行進行排序和記錄。

例如50人以上100人,50人以下200人等。

我在正確的球場嗎?

file = "adultdata.txt" 

def make_data(file): 
    try: 
     f = open(file, "r") 
    except IOError as e: 
     print(e) 
     return none 

large_list = [] 

avg_age = 0 
row_count_under50 = 0 
row_count_over50 = 0 

#create 2 dictionaries per category 

employ_dict_under50 = {} 
employ_dict_over50 = {} 

for row in f: 
    edited_row = row.strip() 
    my_list = edited_row.split(",") 
    try: 
     #Age Category 
     my_list[0] = int(my_list[0]) 

     #Work Category 
     if my_list[-1] == " <=50K": 
      if my_list[1] in employ_dict_under50: 
       employ_dict_under50[my_list[1]] += 1 
      else: 
       employ_dict_under50[my_list[1]] = 1 
       row_count_u50 += 1 

     else: 
      if my_list[1] in emp_dict_o50: 
       employ_dict_over50[my_list[1]] += 1 
      else: 
       employ_dict_over50[my_list[1]] = 1 
       row_count_o50 += 1 

# Other categories here 


print(my_list) 
#print(large_list) 
#return 


# Ignored categories here - e.g. my_list[insert my list numbers here] = None 

回答

0

我沒有訪問您的文件,但我糾正你最在你的代碼有錯誤的有一展身手。

這是我在你的代碼中發現的錯誤的列表:

  • 你的函數make_data基本上是無用的,超出範圍。您需要將其完全刪除
  • 使用文件對象f時,需要使用readline從文件中提取數據。
  • 這也是最好使用IO資源,如文件
  • 你有很多的變化,其被嚴重的內環命名,並且不存在
  • 你宣佈在內環一試無時使用with聲明抓住。你可以刪除這個嘗試,因爲你沒有試圖捕獲任何錯誤

你有一些非常基本的錯誤與通用編程有關,我可以假設你是新來的嗎?如果是這種情況,那麼你應該在線瞭解更多的初學者教程,直到你掌握了你需要使用什麼命令來執行基本任務。

試試你的代碼進行比較,看看是否你能明白我想說:

file = "adultdata.txt" 

large_list = [] 

avg_age = 0 
row_count_under50 = 0 
row_count_over50 = 0 

#create 2 dictionaries per category 

employ_dict_under50 = {} 
employ_dict_over50 = {} 

with open(file, "r") as f: 
    row = f.readline() 

    edited_row = row.strip() 
    my_list = edited_row.split(",") 
    #Age Category 
    my_list[0] = int(my_list[0]) 

    #Work Category 
    if my_list[-1] == " <=50K": 
     if my_list[1] in employ_dict_under50: 
      employ_dict_under50[my_list[1]] += 1 
     else: 
      employ_dict_under50[my_list[1]] = 1 
      row_count_under50 += 1 

    else: 
     if my_list[1] in employ_dict_over50: 
      employ_dict_over50[my_list[1]] += 1 
     else: 
      employ_dict_over50[my_list[1]] = 1 
      row_count_over50 += 1 

# Other categories here 
print(my_list) 
#print(large_list) 
#return 

我不能肯定地說,如果這一代碼將工作或沒有你的文件,但它應該給你是一個開始。