(Python) 如何让用户打开一个文本文件,然后更改一个整数/数字
(Python) How can I let a user open a text file and then change an integer / number
我问过类似的问题,但无济于事。
我是一名编程新手,只学过一些基本技术。任务的一部分是创建一个我大部分时间都完成的食谱程序,只有一个部分阻止我完成。
我应该允许用户调用以前创建的文本文件(我已经完成了这一点),然后在此之后应该显示该文件的内容以供他们查看(我也已经完成了这个位),但是用户应该能够重新计算份量,从而更改配料的数量。因此,如果用户输入:"I want 2 servings" 并且 1 份的原始数量是 100 克,现在应该输出 200 克。
我真的很沮丧,我的老师希望明天能完成这项工作。以下是我应该允许用户执行的操作。
用户应该能够检索食谱并为不同的人数重新计算配料。
• 程序应要求用户输入人数。
• 程序应输出:
• 菜谱名称
• 新增人数
• 为该人数修改后的数量和单位。
我将 post 下面我的实际代码来展示我到目前为止所做的事情,即允许用户查看和制作新食谱。但是缺少修改后的数量位。
如果代码混乱或无组织,我深表歉意,我是新手。
目前代码:
#!/usr/bin/env python
import time
def start():
while True:
user_input = input("\nWhat would you like to do? " "\n 1) - Enter N to enter a new recipe. \n 2 - Enter V to view an exisiting recipe, \n 3 - Enter E - to edit a recipe to your liking. \n 4 - Or enter quit to halt the program " "\n ")
if user_input == "N":
print("\nOkay, it looks like you want to create a new recipe. Give me a moment..." "\n")
time.sleep(1.5)
new_recipe()
elif user_input == "V":
print("\nOkay, Let's proceed to let you view an existing recipe stored on the computer")
time.sleep(1.5)
exist_recipe()
elif user_input == "E":
print("\nOkay, it looks like you want to edit a recipe's servings. Let's proceed ")
time.sleep(1.5)
modify_recipe()
elif user_input == "quit":
return
else:
print("\nThat is not a valid command, please try again with the commands allowed ")
def new_recipe():
new_recipe = input("Please enter the name of the new recipe you wish to add! ")
recipe_data = open(new_recipe, 'w')
ingredients = input("Enter the number of ingredients ")
servings = input("Enter the servings required for this recipe ")
for n in range (1,int(ingredients)+1):
ingredient = input("Enter the name of the ingredient ")
recipe_data.write("\nIngrendient # " +str(n)+": \n")
print("\n")
recipe_data.write(ingredient)
recipe_data.write("\n")
quantities = input("Enter the quantity needed for this ingredient ")
print("\n")
recipe_data.write(quantities)
recipe_data.write("\n")
unit = input("Please enter the unit for this quantity (i.e. g, kg) ")
recipe_data.write(unit)
print("\n")
for n in range (1,int(ingredients)+1):
steps = input("\nEnter step " + str(n)+ ": ")
print("\n")
recipe_data.write("\nStep " +str(n) + " is to: \n")
recipe_data.write("\n")
recipe_data.write(steps)
recipe_data.close()
def exist_recipe():
choice_exist= input("\nOkay, it looks like you want to view an existing recipe. Please enter the name of the recipe required. ")
exist_recipe = open(choice_exist, "r+")
print("\nThis recipe makes " + choice_exist)
print(exist_recipe.read())
time.sleep(1)
def modify_recipe():
choice_exist = input("\nOkay, it looks like you want to modify a recipe. Please enter the name of this recipe ")
exist_recipe = open(choice_exist, "r+")
servrequire = int(input("Please enter how many servings you would like "))
start()
编辑:
下面是创建文本文件(配方)及其输出的示例(该文件名为 bread.txt)注意 输出有点乱,我会尽快修复可以让程序的核心工作。
创建食谱
What would you like to do?
1) - Enter N to enter a new recipe.
2 - Enter V to view an exisiting recipe,
3 - Enter E - to edit a recipe to your liking.
4 - Or enter quit to halt the program
N
Okay, it looks like you want to create a new recipe. Give me a moment...
Please enter the name of the new recipe you wish to add! bread.txt
Enter the number of ingredients 3
Enter the servings required for this recipe 1
Enter the name of the ingredient flour
Enter the quantity needed for this ingredient 300
Please enter the unit for this quantity (i.e. g, kg) g
Enter the name of the ingredient salt
Enter the quantity needed for this ingredient 50
Please enter the unit for this quantity (i.e. g, kg) g
Enter the name of the ingredient water
Enter the quantity needed for this ingredient 1
Please enter the unit for this quantity (i.e. g, kg) l
Enter step 1: pour all ingredients into a bowl
Enter step 2: mix together
Enter step 3: put in a bread tin and bake
查看食谱
What would you like to do?
1) - Enter N to enter a new recipe.
2 - Enter V to view an exisiting recipe,
3 - Enter E - to edit a recipe to your liking.
4 - Or enter quit to halt the program
V
Okay, Let's proceed to let you view an existing recipe stored on the computer
Okay, it looks like you want to view an existing recipe. Please enter the name of the recipe required. bread.txt
This recipe makes bread.txt
Ingrendient # 1:
flour
300
g
Ingrendient # 2:
salt
50
g
Ingrendient # 3:
water
1
l
Step 1 is to:
pour all ingredients into a bowl
Step 2 is to:
mix together
Step 3 is to:
put in a bread tin and bake
这里是输入 V 的输出:
这个食谱使 bread.txt
Ingrendient # 1:
flour
300
g
Ingrendient # 2:
salt
50
g
Ingrendient # 3:
water
1
l
Step 1 is to:
pour all ingredients into a bowl
Step 2 is to:
mix together
Step 3 is to:
put in a bread tin and bake
期待您的回复。
您的食谱文件看起来像这样:
Ingrendient # N:
{INGREDIENT}
{AMOUNT}
{METRIC}
...
(After N ingredients...)
Step N:
{INSTRUCTIONS}
所以基本上你想一次读四行,丢弃第一行,然后将其余的分配给有用的东西。
with open(path_to_recipe) as infile:
ingredients = []
while True:
try:
sentinel = next(infile) # skip a line
if sentinel.startswith("Step"):
# we're past the ingredients, so
break
name = next(infile)
amount = next(infile)
metric = next(infile)
except StopIteration:
# you've reached the end of the file
break
ingredients.append({'name':name, 'amount':float(amount), 'metric':metric})
# use a dictionary for easier access
当我们退出with
块时,ingredients
将是一个字典列表,可以使用如下:
for ingredient in ingredients:
scaled_volume = ingredient['amount'] * scale # double portions? etc...
print(scaled_volume, ingredient['metric'], " ", ingredient['name'])
# # RESULT IS:
300g flour
50g salt
1l water
你应该能够利用所有这些来完成你的任务!
我问过类似的问题,但无济于事。
我是一名编程新手,只学过一些基本技术。任务的一部分是创建一个我大部分时间都完成的食谱程序,只有一个部分阻止我完成。
我应该允许用户调用以前创建的文本文件(我已经完成了这一点),然后在此之后应该显示该文件的内容以供他们查看(我也已经完成了这个位),但是用户应该能够重新计算份量,从而更改配料的数量。因此,如果用户输入:"I want 2 servings" 并且 1 份的原始数量是 100 克,现在应该输出 200 克。
我真的很沮丧,我的老师希望明天能完成这项工作。以下是我应该允许用户执行的操作。
用户应该能够检索食谱并为不同的人数重新计算配料。
• 程序应要求用户输入人数。
• 程序应输出:
• 菜谱名称
• 新增人数
• 为该人数修改后的数量和单位。
我将 post 下面我的实际代码来展示我到目前为止所做的事情,即允许用户查看和制作新食谱。但是缺少修改后的数量位。
如果代码混乱或无组织,我深表歉意,我是新手。
目前代码:
#!/usr/bin/env python
import time
def start():
while True:
user_input = input("\nWhat would you like to do? " "\n 1) - Enter N to enter a new recipe. \n 2 - Enter V to view an exisiting recipe, \n 3 - Enter E - to edit a recipe to your liking. \n 4 - Or enter quit to halt the program " "\n ")
if user_input == "N":
print("\nOkay, it looks like you want to create a new recipe. Give me a moment..." "\n")
time.sleep(1.5)
new_recipe()
elif user_input == "V":
print("\nOkay, Let's proceed to let you view an existing recipe stored on the computer")
time.sleep(1.5)
exist_recipe()
elif user_input == "E":
print("\nOkay, it looks like you want to edit a recipe's servings. Let's proceed ")
time.sleep(1.5)
modify_recipe()
elif user_input == "quit":
return
else:
print("\nThat is not a valid command, please try again with the commands allowed ")
def new_recipe():
new_recipe = input("Please enter the name of the new recipe you wish to add! ")
recipe_data = open(new_recipe, 'w')
ingredients = input("Enter the number of ingredients ")
servings = input("Enter the servings required for this recipe ")
for n in range (1,int(ingredients)+1):
ingredient = input("Enter the name of the ingredient ")
recipe_data.write("\nIngrendient # " +str(n)+": \n")
print("\n")
recipe_data.write(ingredient)
recipe_data.write("\n")
quantities = input("Enter the quantity needed for this ingredient ")
print("\n")
recipe_data.write(quantities)
recipe_data.write("\n")
unit = input("Please enter the unit for this quantity (i.e. g, kg) ")
recipe_data.write(unit)
print("\n")
for n in range (1,int(ingredients)+1):
steps = input("\nEnter step " + str(n)+ ": ")
print("\n")
recipe_data.write("\nStep " +str(n) + " is to: \n")
recipe_data.write("\n")
recipe_data.write(steps)
recipe_data.close()
def exist_recipe():
choice_exist= input("\nOkay, it looks like you want to view an existing recipe. Please enter the name of the recipe required. ")
exist_recipe = open(choice_exist, "r+")
print("\nThis recipe makes " + choice_exist)
print(exist_recipe.read())
time.sleep(1)
def modify_recipe():
choice_exist = input("\nOkay, it looks like you want to modify a recipe. Please enter the name of this recipe ")
exist_recipe = open(choice_exist, "r+")
servrequire = int(input("Please enter how many servings you would like "))
start()
编辑:
下面是创建文本文件(配方)及其输出的示例(该文件名为 bread.txt)注意 输出有点乱,我会尽快修复可以让程序的核心工作。
创建食谱
What would you like to do?
1) - Enter N to enter a new recipe.
2 - Enter V to view an exisiting recipe,
3 - Enter E - to edit a recipe to your liking.
4 - Or enter quit to halt the program
N
Okay, it looks like you want to create a new recipe. Give me a moment...
Please enter the name of the new recipe you wish to add! bread.txt
Enter the number of ingredients 3
Enter the servings required for this recipe 1
Enter the name of the ingredient flour
Enter the quantity needed for this ingredient 300
Please enter the unit for this quantity (i.e. g, kg) g
Enter the name of the ingredient salt
Enter the quantity needed for this ingredient 50
Please enter the unit for this quantity (i.e. g, kg) g
Enter the name of the ingredient water
Enter the quantity needed for this ingredient 1
Please enter the unit for this quantity (i.e. g, kg) l
Enter step 1: pour all ingredients into a bowl
Enter step 2: mix together
Enter step 3: put in a bread tin and bake
查看食谱
What would you like to do?
1) - Enter N to enter a new recipe.
2 - Enter V to view an exisiting recipe,
3 - Enter E - to edit a recipe to your liking.
4 - Or enter quit to halt the program
V
Okay, Let's proceed to let you view an existing recipe stored on the computer
Okay, it looks like you want to view an existing recipe. Please enter the name of the recipe required. bread.txt
This recipe makes bread.txt
Ingrendient # 1:
flour
300
g
Ingrendient # 2:
salt
50
g
Ingrendient # 3:
water
1
l
Step 1 is to:
pour all ingredients into a bowl
Step 2 is to:
mix together
Step 3 is to:
put in a bread tin and bake
这里是输入 V 的输出:
这个食谱使 bread.txt
Ingrendient # 1:
flour
300
g
Ingrendient # 2:
salt
50
g
Ingrendient # 3:
water
1
l
Step 1 is to:
pour all ingredients into a bowl
Step 2 is to:
mix together
Step 3 is to:
put in a bread tin and bake
期待您的回复。
您的食谱文件看起来像这样:
Ingrendient # N:
{INGREDIENT}
{AMOUNT}
{METRIC}
...
(After N ingredients...)
Step N:
{INSTRUCTIONS}
所以基本上你想一次读四行,丢弃第一行,然后将其余的分配给有用的东西。
with open(path_to_recipe) as infile:
ingredients = []
while True:
try:
sentinel = next(infile) # skip a line
if sentinel.startswith("Step"):
# we're past the ingredients, so
break
name = next(infile)
amount = next(infile)
metric = next(infile)
except StopIteration:
# you've reached the end of the file
break
ingredients.append({'name':name, 'amount':float(amount), 'metric':metric})
# use a dictionary for easier access
当我们退出with
块时,ingredients
将是一个字典列表,可以使用如下:
for ingredient in ingredients:
scaled_volume = ingredient['amount'] * scale # double portions? etc...
print(scaled_volume, ingredient['metric'], " ", ingredient['name'])
# # RESULT IS:
300g flour
50g salt
1l water
你应该能够利用所有这些来完成你的任务!