(Python) 如何让用户打开文本文件然后更改整数/数字 [英] (Python) How can I let a user open a text file and then change an integer / number

查看:18
本文介绍了(Python) 如何让用户打开文本文件然后更改整数/数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我问过一个类似的问题,但无济于事.

I've asked a similar question but to no avail.

我是一名编程新手,只教过一些基本技术.任务的一部分是创建一个我主要完成的食谱程序,只有一个部分阻止我完成.

I am a novice programming student and I've only been taught some basic techniques. Part of a task is to create a recipe program which I've mostly done, there is just one part preventing me from finishing.

我应该允许用户调用以前创建的文本文件(我已经完成了这一点),然后应该显示该文件的内容供他们查看(我也完成了这一点),但是用户应该能够重新计算份量,从而更改成分的数量.因此,如果用户输入:我想要 2 份"并且 1 份的原始数量是 100 克,现在应该输出 200 克.

I am supposed to allow a user to call a previously created text file (I've done this bit), then after this the contents of this file should be displayed for them to see (I've also done this bit), however the user should be able to recalculate the servings and therefore change the quantity of the ingredients. So if the user entered: "I want 2 servings" and the original quantity for 1 serving was 100g it should now output 200g.

这真的让我很沮丧,我的老师期待明天的工作.以下是我应该允许用户执行的操作.

It is really frustrating me and my teacher expects this work tomorrow. Below is what I am supposed to allow the user to do.

用户应该能够检索食谱并为不同数量的人重新计算成分.

The user should be able to retrieve the recipe and have the ingredients recalculated for a different number of people.

• 程序应要求用户输入人数.

• The program should ask the user to input the number of people.

• 程序应该输出:

• 配方名称

• 新人数

• 修订后的数量,以及该人数的单位.

• the revised quantities with units for this number of people.

我将在下面发布我的实际代码,以展示我到目前为止所做的工作,即允许用户查看和制作新食谱.但是缺少修改后的数量位.

I will post my actual code below to show what I have done so far, which is to allow a user to view and make a new recipe. But the revised quantities bit is missing.

如果代码混乱或无组织,我深表歉意,我是新手.

目前的代码:

#!/usr/bin/env python

import time

def start():

    while True:

        user_input = input("
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 " "
 ")

        if user_input == "N":
            print("
Okay, it looks like you want to create a new recipe. Give me a moment..." "
")
            time.sleep(1.5)
            new_recipe()

        elif user_input == "V":
            print("
Okay, 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("
Okay, 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("
That 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("
Ingrendient # " +str(n)+": 
")
        print("
")
        recipe_data.write(ingredient)
        recipe_data.write("
")
        quantities = input("Enter the quantity needed for this ingredient ")
        print("
")
        recipe_data.write(quantities)
        recipe_data.write("
")
        unit = input("Please enter the unit for this quantity (i.e. g, kg) ")
        recipe_data.write(unit)
        print("
")

    for n in range (1,int(ingredients)+1):
        steps = input("
Enter step " + str(n)+ ": ")
        print("
")
        recipe_data.write("
Step " +str(n) + " is to: 
")
        recipe_data.write("
")
        recipe_data.write(steps)
    recipe_data.close()

def exist_recipe():
    choice_exist= input("
Okay, 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("
This recipe makes " + choice_exist)
    print(exist_recipe.read())
    time.sleep(1)

def modify_recipe():
    choice_exist = input("
Okay, 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) 注意输出有点乱,我会在获得核心内容后修复它程序工作.

Below is an example creation of a text file (recipe) and it's output (the file is called bread.txt) Note the outputs are a bit messy, I will fix that once I can get the core of the program to work.

创建食谱

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,这里是输出:

And here is the output if you enter V:

这个食谱做面包.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

期待您的回复.

推荐答案

看起来你的配方文件是这样的:

It looks like your recipe files look like this:

Ingrendient # N: 
{INGREDIENT}
{AMOUNT}
{METRIC}
...
(After N ingredients...)
Step N: 
{INSTRUCTIONS}

所以基本上你想一次读四行,丢弃第一行,然后把剩下的分配给有用的东西.

So basically you want to read four lines at a time, discard the first, then assign the rest to something useful.

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 将是一个可以使用的字典列表,如下所示:

When we exit the with block, ingredients will be a list of dictionaries that can be used as follows:

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

你应该能够利用所有这些来完成你的任务!

You should be able to leverage all that to finish your assignment!

这篇关于(Python) 如何让用户打开文本文件然后更改整数/数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆