2014-11-05 1 views
0

나는 조리법을 만들 수있는 순간에 조리법 책을 만들지 만, 이제는 저장된 조리법을 검색하고 표시하는 모듈을 만들기 시작합니다.텍스트 파일의 내용 반환 및 다른 값 인쇄

윌리엄스 특별 레시피

성분 :

빵 : 120g 버터 : 1,234g

순간

나는의 라인을 따라 내용으로이 .txt 문서가

레시피 : 12

그런 다음 얼마나 많은 레시피를 제공하는지에 따라 사용자에게 몇 가지 물량을 곱해야합니다. 그런 다음 다시 전체 레서피를 인쇄해야합니다.

코드화 된 응답을 대답으로 요구하지 않고이 결과를 얻는 방법에 대해 궁금해하고 있었지만,이 작업과 필요한 특정 기능에 어떻게 접근 할 것인지 크게 평가할 것입니다.

저는 지금까지 제 코드를 포함 시켰습니다. 사실은 믿을 수 없을 정도로 비 체계적이었고 이해하기 힘들었던 점을 고맙게 생각합니다. 그러나 나는 그것을 참고로 포함 시켰습니다.

는 (나는 또한 사용자에게 모든 조리법을 표시하는 방법으로 나중에 구현 될 것입니다 생성 된 모든 조리법의 .txt 파일을 만들었습니다,하지만 순간에 그냥 검색에 설정되어 있습니다.)

#Recipe Task 

import os.path 

def file_(n): 
    if n == "listR" : 
     list_f = open("list_recipes.txt", "a+") 
     list_f.write(new_name + "\n") 
    if n == "oar": #open append read 
     f=open(new_name + ".txt","a+") 
    elif n == "c": #closes file 
     f.close() 


def print_line(x): #ease of printing multiple lines to break up text 
    for c in range(x): 
     print "" 

def new_ingredients(): #adding new ingredients 
    f.write("Ingredients:" + "\n" + "\n") 
    fin_ingredient = False 
    while fin_ingredient != True : 
     input_ingredient = raw_input("New ingredient:" + "\n").lower() 
     split_ingred = input_ingredient.split() 
     if input_ingredient == "stop": #stops asking questions when user types 'stop' 
      fin_ingredient = True 
     else : 
      f.write(split_ingred[0] + ":" + " " + split_ingred[1] + " " + split_ingred[2] + "\n") 

def search_recipe(n): #searching for recipes 
    n = n + ".txt" 
    if os.path.isfile('/Users/wjpreston/Desktop/' + n) == True : 
     print "Recipe Found..." 
     found_recipe = open(n) 
     print found_recipe.read() 
     append_serving = raw_input("Would you like to change the number of people you are serving?" + "\n").lower() 
     if append_serving == "yes" : 
      appended_serving = input("How many would you like to serve?" + "\n") 

      with open(n) as f: #here is my issue - not sure where to go with this!! 
       list_recipe = f.readlines() 

      found_recipe.close() 
     else : 
      print "fail" 



    else: 
     print "No existing recipes under that name have been found." 







print "Welcome to your Recipe Book" 
print_line(3) 

recipe_phase = raw_input("Are you 'creating' a recipe or 'viewing' an existing one?" + "\n").lower() 

if recipe_phase == "creating": 

    new_name = raw_input("Name of Recipe: " + "\n") 
    file_("listR") 
    file_("oar") 
    f.write("------------" + "\n" + new_name + "\n" + "\n") 
    print "Ingrediants required in the format 'ingredient quantity unit' - type 'stop' to end process" 
    new_ingredients() 
    new_num = input("Number serving: ") 
    f.write("\n" + "Recipe Serves: " + str(new_num) + "\n" "\n" + "\n") 
    file_("c") 



elif recipe_phase == "viewing": 
    search = raw_input("Search for recipe: ") 
    search_recipe(search) 
+0

이 질문은 ... 꽤 광범위합니다. 정확히 무엇을 찾고 있는지 잘 모르겠습니다. – Ajean

+0

죄송합니다, 이곳은 새로운 곳입니다. 그럼에도 불구하고 응답을 감사하십시오. 조리법을 별도의 텍스트 파일에 저장 한 다음 검색 할 때 리콜했지만 얼마나 많은 사람들이 제공되는지에 따라 재료에 다른 값을 반환했습니다. 따라서 120 그램의 경우 12 명이 사용됩니다.하지만 나는 24 개를 제공하고 있으므로이 재료 240 그램을 인쇄하고 싶습니다. 사용자에게 다른 값을 반환하고 싶습니다. 희망이 물건을 지워. – WJPreston

답변

0

저는 문자열 처리 전문가는 아니지만 다음과 같은 방법으로 문제에 접근합니다.
각 줄을 새 줄에 저장하십시오.
로드 된 문자열을 "\ n"로 나눕니다.

e.g. {"bread": grams, "butter": grams} 

다음은 또한 어떻게 저장해야합니다 : 두 dicts, 실제 데이터 각 성분의 유형

e.g. {"bread": 4, "butter": 7} 

하나 하나를 만드는 동안
그런 다음 일부-루프로 목록을 처리 많은 레시피가 작성, 어쩌면 성분의 순서 (dicts는 임의의 순서로 저장된다) 역할 :, 그 후

e.g. ["bread", "butter"] 

당신 당신의 costumer에게 그가 얼마나 많은 봉사를했는지 그리고 마지막으로 최종 결과를 계산하고 인쇄 할 수 있습니다.

for ing in ing_order: 
     print ing+":", ing_amount[ing]*requested_serves/default_seves, ing_types[ing] 

... hopyfully 당신은 여전히 ​​충분한 challange 있고, 잘하면 당신의 질문을 올바르게 이해했습니다.

+0

예, 위에 포함 된 레서피의 형식 지정에 대한 몇 가지 이유로 잘못된 요소가 모두 자체 줄에 있습니다. 그래도 답변 해 주셔서 대단히 감사합니다. 당신이하고있는 일을 이해하고 당신의 접근법에 대해 아마도 고맙습니다. 한 가지 질문은 텍스트 파일의 각 줄을 목록에 저장하는 방법을 이해합니다. 그러나 위의 규칙을 적용해야하는 성분 필드인지 어떻게 결정합니까? – WJPreston

+0

@WJPreston 'ingredients' 변수를 만듭니다. for-loop로리스트를 처리하십시오. 현재 요소가''Ingredients : "'인 경우,'ingredients'를'True'로 설정하십시오. 그런 다음 for 루프에서도 if 문을 추가 할 수 있습니다. 'if element [: 13] == "Recipe Serves": process_serves, elif ingredients == True : process_ingredient'. 확실히 더 우아한 방법이 있습니다 (어쩌면 하나를 찾으십니까?), 적어도 당신에게는 생각이 있습니다. – Nearoo

+0

아, 이제 더 많은 것을 이해하기 시작했습니다. 당신의 노력에 감사드립니다. 나는 Python에 익숙하지 않고 응답에 크게 감사한다. – WJPreston