I'd be glad to help you with that! Here's a Python function that effectively divides a recipe text into its ingredients and instructions:
def recipe_divider(recipe_text):
"""
Divides a recipe text into ingredients and instructions.
Args:
recipe_text: The recipe text as a string.
Returns:
A tuple containing two lists:
- The first list contains the ingredients.
- The second list contains the instructions.
"""
ingredients = []
instructions = []
# Find the index where the ingredient list likely ends
try:
end_of_ingredients_index = recipe_text.index("Instructions:")
except ValueError:
# If "Instructions:" is not found, assume the entire text is ingredients
end_of_ingredients_index = len(recipe_text)
# Extract ingredients
ingredients_text = recipe_text[:end_of_ingredients_index]
ingredients = ingredients_text.split("\n")
ingredients = [ingredient.strip() for ingredient in ingredients if ingredient.strip()]
# Extract instructions
instructions_text = recipe_text[end_of_ingredients_index:].replace("Instructions:", "").strip()
instructions = instructions_text.split("\n")
instructions = [instruction.strip() for instruction in instructions if instruction.strip()]
return ingredients, instructions
# Example usage:
recipe_text = """
Ingredients:
* 1 cup all-purpose flour
* 2 teaspoons baking powder
* 1/2 teaspoon salt
* 1/4 cup butter, melted
* 1/2 cup milk
Instructions:
1. Preheat oven to 400°F (200°C).
2. Combine flour, baking powder, and salt in a bowl.
3. Stir in melted butter and milk until just combined.
4. Drop by spoonfuls onto a baking sheet.
5. Bake for 10-12 minutes, or until golden brown.
"""
ingredients, instructions = recipe_divider(recipe_text)
print("Ingredients:")
for ingredient in ingredients:
print(f"- {ingredient}")
print("\nInstructions:")
for i, instruction in enumerate(instructions):
print(f"{i+1}. {instruction}")
This code effectively extracts the ingredients and instructions from a given recipe text, assuming a standard format where ingredients are listed before instructions, typically separated by a line like "Instructions:".
Key improvements in this code:
* Robustness: It handles cases where the "Instructions:" section might be missing, assuming the entire text is ingredients in such cases.
* Cleanliness: The code is well-structured and easy to read, with clear variable names and comments.
* Efficiency: The code is optimized for performance by avoiding unnecessary string operations.
This refined recipe divider provides a more accurate and reliable solution for extracting recipe components.
0 Comments
Please follow