我有一個我正在使用的文件。我想創建一個讀取文件並將內容放入字典的函數。然後該字典需要通過主函數傳遞。這是主程序。它不能改變。我所做的一切都必須與主程序一起工作。創建打開文件並創建字典的功能
def main():
sunspot_dict = {}
file_str = raw_input("Open what data file: ")
keep_going = True
while keep_going:
try:
init_dictionary(file_str, sunspot_dict)
except IOError:
print "Data file error, try again"
file_str = raw_input("Open what data file: ")
continue
print "Jan, 1900-1905:", avg_sunspot(sunspot_dict, (1900,1905),(1,1))
print "Jan-June, 2000-2011:", avg_sunspot(sunspot_dict, (2000,2011), (1,6))
print "All years, Jan:", avg_sunspot(sunspot_dict, month_tuple=(1,1))
print "All months, 1900-1905:", avg_sunspot(sunspot_dict, year_tuple=(1900,1905))
try:
print "Bad Year Key example:", avg_sunspot(sunspot_dict, (100,1000), (1,1))
except KeyError:
print "Bad Key raised"
try:
print "Bad Month Index example:", avg_sunspot(sunspot_dict, (2000,2011), (1,100))
except IndexError:
print "Bad Range raised"
keep_going = False
print "Main function finished normally."
print sunspot_dict
這是我到目前爲止有:
def init_dictionary(file_str, sunspot_dict):
line = open(file_str, "rU")
sunspot_dict = {}
for i in line:
sunspot_dict[i]
print sunspot_dict
@KarlKnechtel我不知道如何繼續。也許我正在理解錯誤的問題。以下是作業內容: init_dictionary(file_string,sunspot_dict)。該函數將參數作爲要打開的文件的名稱和一個空字典。它沒有返回值,但是填充字典的值。關鍵應該是一年;該數據應該是該年的月份的太陽黑子數據列表。 難道是說使用__init__函數在類下執行此操作嗎?或者我應該創建一個名爲init_dictionary(file_string,sunspot_dict)的普通函數? – SimplyZ