2014-03-31 210 views
1

我是Python的新手,需要我的程序幫助。我的問題現在已經得到解答,感謝所有幫助我的人!Python編程 - 輸入/輸出

+0

你有沒有想過使用不同的文件格式?只需使用pickle,JSON,xml等等進行存儲等等。它不需要那麼複雜! :-) – dawg

回答

1

而不是試圖解析一個文本文件自己,我會建議你使用的現成的工具之一Python標準庫做的工作適合你。有幾種不同的可能性,包括configparsercsvshelve。但對於我的示例,我將使用json

json模塊允許您Python對象保存到一個文本文件中。由於您想按名稱搜索食譜,因此創建食譜字典然後將其保存到文件將是一個好主意。

每個配方也將是一個字典,並且將存儲在名稱食譜數據庫。因此,開始時,你input_func需要返回配方字典,像這樣:

def input_func(): #defines the input_function function 
    ... 
    return { 
     'name': name, 
     'people': people, 
     'ingredients': ingredients, 
     'quantity': quantity, 
     'units': units, 
     'num_ing': num_ing, 
     } 

現在我們需要幾個開簡單的功能和保存食譜數據庫:

def open_recipes(path): 
    try: 
     with open(path) as stream: 
      return json.loads(stream.read()) 
    except FileNotFoundError: 
     # start a new database 
     return {} 

def save_recipes(path, recipes): 
    with open(path, 'w') as stream: 
     stream.write(json.dumps(recipes, indent=2)) 

就是這樣!現在,我們可以把它的所有工作:

# open the recipe database 
recipes = open_recipes('recipes.json') 

# start a new recipe 
recipe = input_func() 

name = recipe['name'] 

# check if the recipe already exists 
if name not in recipes: 
    # store the recipe in the database 
    recipes[name] = recipe 
    # save the database 
    save_recipes('recipes.json', recipes) 
else: 
    print('ERROR: recipe already exists:', name) 
    # rename recipe... 

... 

# find an existing recipe 
search_name = str(input("What is the name of the recipe you wish to retrieve?")) 

if search_name in recipes: 
    # fetch the recipe from the database 
    recipe = recipes[search_name] 
    # display the recipe... 
else: 
    print('ERROR: could not find recipe:', search_name) 

我已經明顯留下了一些重要的功能,爲您制定出(如如何顯示的配方,如何重命名/編輯配方等)。

+0

非常感謝!這真的很有幫助。 :) – Matt

+0

@會。這可能是因爲你沒有先打開食譜數據庫。在嘗試執行搜索之前,您需要執行'recipes = open_recipes('recipes.json')'(參見我的示例代碼)。 – ekhumoro