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

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

问题描述

我曾经问过一个类似的问题,但没有成功。

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

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



真让我很沮丧,我的老师期待明天这项工作。以下是我应该允许用户做的事情。



用户应该能够检索配方,并为不同数量的人重新计算配料。 / b>

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

•程序输出:



•食谱名称



•新人数

•修改后的数量,单位为这个数字。

我会在下面发表我的实际代码,以显示我迄今所做的工作,允许用户查看并制作新配方。但是修改后的数量是不存在的。

我很抱歉,如果代码是杂乱无章的,我是新手。



代码至今: $!
$ b

 #!/ usr / bin / env python 

导入时间
$ b $ def start():

True:

user_input = input (\ n您想要做什么?\\\
1) - 输入N来输入一个新的配方\\\
2 - 输入V来查看现有的配方\ n 3 - 输入E - 编辑如果用户输入==N:
print(\\\\\\)不,你看,你想创造一个新的食谱,给我一下......\\\

time.sleep(1.5)
new_recipe()

elif user_input ==V:
print(\\\
Okay,让我们继续让您查看存储在计算机上的现有配方)
time.sl eep(1.5)
exists_recipe()

elif user_input ==E:
print(\\\
Okay,看起来好像要编辑食谱的食谱。让我们继续)
time.sleep(1.5)
modify_recipe()

elif user_input ==quit:
return

否则:
print(\\\
不是有效的命令,请用允许的命令再试一次)

$ b def new_recipe():
new_recipe =输入(请输入您希望添加的新配方的名称!)
recipe_data = open(new_recipe,'w')
成分=输入(输入配料数量)
份数=输入(输入此配方所需的份数)

在范围内(1,int(成分)+1):

成分=输入(输入配料的名称)
recipe_data.write(\\\
Ingrendient#+ str(n)+:\\\

print(\\\

recipe_data.write(成分)
recipe_data.write(\\\

数量=输入(输入此成分所需的数量)
print(\ n)
recipe_data.write(数量)
recipe_data.write(\\\

unit = input(请输入单位这个数量(即(1,int(成分)+1)
print(\ n)


steps = input(\\\
Enter step+ str(n)+:)
print(\\\

recipe_data.write(\\\
Step + str(n)+是:\\\

recipe_data.write(\\\

recipe_data.write(steps)
recipe_data.close()

def exists_recipe():
choice_exist =输入(\\\
Okay,它看起来像你想查看一个现有的配方,请输入所需的配方名称)
(b)打印(打印)打印(打印)打印(选择打印)打印
$ def def modify_recipe():
choice_exist = input(\\\
Okay,它看起来像你想修改一个配方,请输入这个配方的名称)
exist_recipe = open (choice_exist,r +)
servrequire = int(input(Plea ())


start()

以下是创建一个文本文件(配方)和它的输出的示例(该文件被称为面包.txt)注意输出有点麻烦,我会修正一次,我可以让程序的核心工作。

创建配方

 您想要做什么? 
1) - 输入N以输入新配方。
2 - 输入V来查看现有的配方,
3 - 输入E - 编辑您喜欢的配方。
4 - 或者输入quit停止程序
N

好​​的,看起来你想创建一个新的配方。给我一点时间...

请输入您希望添加的新配方的名称! bread.txt
输入配料的数量3
输入配方所需的份量1
输入配料面粉的名称


输入此成分所需的数量300


请为此数量输入单位(即g,kg)g


输入配料的名称盐


输入这种成分所需的数量50


请输入此数量的单位(即g,kg)g


输入配料水的名称


输入此配料所需的数量1


请输入单位数量(即克,千克)l



进入步骤1:将所有材料倒入碗中



输入步骤2:混合在一起



输入步骤3:放入面包罐并烘烤
$ b $ p 查看配方

 你想干什么? 
1) - 输入N以输入新配方。
2 - 输入V来查看现有的配方,
3 - 输入E - 编辑您喜欢的配方。
4 - 或输入quit停止程序
V

好​​的,让我们继续看看存储在电脑上的现有配方

好​​的,它看起来像你想要查看现有的食谱。请输入所需配方的名称。 bread.txt

这个食谱使bread.txt

外单元1:
面粉
300
g
外教#2 :
salt
50
g
外商#3:

1

步骤1:

将所有配料倒入碗中
步骤2:将

混合在一起
步骤3将:

放入面包锡和烘烤

这里是输入V:



这个食谱使bread.txt

  Ingrendient#1:
面粉
300
g
外商#2:

50
g
外商#3:

1
l
第1步是:

将所有材料倒入碗中
步骤2是:

混合
步骤3是:

放入面包罐并烘烤

我期待着您的回复。

解决方案

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

  Ingrendient#N:
{INGREDIENT}
{AMOUNT}
{METRIC}
...
(在N种成分之后...)
步骤N:
{指令}

所以基本上你想一次读四行,放弃第一行,然后把其余的分配给一些有用的东西。

  with打开(path_to_recipe)作为infile:
成分= []
而真:
尝试:
sentinel = next(infile)#跳过一行
如果sentinel.startswith (步骤):
#我们已经超过配料,所以
break
name = next(infile)
amount = next(infile)
metric =下一个(infile)
除了StopIteration:
#你已经到达文件的末尾了
break
ingredients.append({'name':name,'amount':float (amount),'metric':metric})
#使用一个字典来更方便地访问

当我们用块退出时,成分将成为一个字典列表,可以使用如下:

  
scaled_volume =成分['amount'] * scale#double parts?等等...
print(scaled_volume,ingredients ['metric'],,ingredient ['name'])
##结果是:
300克面粉
50克盐
1l water

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

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.

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 program should output:

• the recipe name

• the new 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.

I apologise if the code is messy or unorganised, I am new to this.

Code so far:

#!/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()

EDIT:

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.

Creating a recipe

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

Viewing a recipe

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

And here is the output if you enter V:

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

I look forward to your replies.

解决方案

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

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天全站免登陆