(Python) 如何让用户打开文本文件,然后更改整数/数字

2024-01-02

我曾问过类似的问题,但没有结果。

我是一名编程新手,只教过一些基本技术。任务的一部分是创建一个食谱程序,我大部分时间都完成了这个程序,只有一个部分阻止我完成。

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

这真的让我很沮丧,我的老师希望明天能完成这项工作。以下是我应该允许用户执行的操作。

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

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

• 程序应输出:

• 菜谱名称

• 新人数

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

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

如果代码混乱或无组织,我深表歉意,我对此很陌生。

到目前为止的代码:

#!/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:

下面是创建文本文件(配方)及其输出的示例(该文件称为 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,则输出如下:

这个食谱制作面包.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 block, 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

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

(Python) 如何让用户打开文本文件,然后更改整数/数字 的相关文章

随机推荐

  • 创建 (ES6) 承诺而不开始解决它

    使用 ES6 Promise 如何在不定义解决逻辑的情况下创建 Promise 这是一个基本示例 一些 TypeScript var promises function waitFor key string Promise
  • Visual Studio 2013 中的“新建项目”对话框中缺少项目模板

    当我点击文件 gt 新建 gt 项目在 Visual Studio 2013 中 不存在任何项目模板 但是 在解决方案文件中 显然是在 Visual Studio 的另一个版本中创建的 当我尝试时 添加 gt 新项目 所有模板都在那里 我想
  • Swift 中的强引用和弱引用

    在 Objective C 中 您可以将属性定义为具有强引用或弱引用 如下所示 property strong property weak 这是如何快速完成的 直接从斯威夫特语言指南 https developer apple com li
  • MainActivity 关闭后停止服务(已编辑)

    我认为我根本不清楚 我确实希望该服务能够持续存在 即使主要活动通过用户操作被破坏或Android系统这样做 它做得很好 但是当应用程序在某个时刻重新打开时 我会想要检查如果背景活动存在并使用操作按钮停止它 请提前谢谢 我启动了后台服务 在我
  • 我需要做什么才能让 Hash.from_xml() 工作?

    我在代码中安装了 ActiveSupport 并需要 active support 但是当我尝试使用Hash from xml method 我缺少什么 gem list returns LOCAL GEMS activesupport 3
  • 如何从另一个变量名创建变量? [复制]

    这个问题在这里已经有答案了 好的 在 php 中我该怎么做 给定以下场景 array of letters var letters array a b c loop through array and create empty arrays
  • 在最接近的日期合并数据框

    我有一些实验的一些数据 按主题 ID 和日期索引 我想将数据连接在一起 但受试者可能在不同的日子进行实验 这是我的意思的一个例子 下图是两个不同实验的结果 SubjectID Date ScoreA 1 2016 09 20 10 1 20
  • Java 10 'var' 和继承

    经过审查后var所见特征here http openjdk java net jeps 286 我在使用 JDK 10 设置 Eclipse IntelliJ IDEA IDE 时遇到了困难 因此向拥有 Java 10 工作环境的 Stac
  • POSIX 目录名的 PowerShell 等效项

    这个问题 https stackoverflow com questions 778135 how do i get the equivalent of dirname in a batch file询问如何在批处理脚本中获取路径的目录名称
  • 将csv数据转换为特定格式的嵌套json

    将 csv 数据转换为 json 并添加新的字段名称 parsed address 并基于地址类型值将放置在 parsed address 字段中 我可以创建 parsed address 字段并将地址列放置在其下方 但地址字段应根据 ad
  • 引导程序文件的示例?

    有谁有一个很好的引导程序类示例 我可以看到以供参考 我似乎找不到任何地方 搜索谷歌但没有运气 搜索了帮助文件 没有运气 如果您正在搜索在应用程序开始时配置容器的类 您可以下载最新的Prism http compositewpf codepl
  • PHP 应用程序的单元、集成和系统测试 [关闭]

    Closed 这个问题需要多问focused help closed questions 目前不接受答案 我们接到一项任务 为客户社区开发原型 有人建议 PHP 作为编程语言 但我们不应该实际编码它 只需要一个带有文档的原型 我想知道这样的
  • 如何向 C# 控制台应用程序添加计时器

    就是这样 如何向 C 控制台应用程序添加计时器 如果您能提供一些示例编码 那就太好了 这非常好 但是为了模拟一段时间的流逝 我们需要运行一个需要一些时间的命令 这在第二个示例中非常清楚 然而 使用 for 循环执行某些功能的方式永远会占用大
  • 找到图像中每个像素最接近的 RGB 颜色

    我正在使用 NumPy 进行一些图像处理 我将图像加载到数组中并获取每个像素的 最近 颜色 如下所示 rgbValues is a global list with 22 RGB values def getNearestColor rgb
  • 在SVG中绕其自身中心旋转矩形

    我有以下代码
  • 如何在 Ubuntu/Debian 上安装特定版本的 Node?

    我想在 Ubuntu 12 04 上安装 NodeJS 版本 0 8 18 我尝试安装最新版本 然后使用恢复到 0 8 18nvm 但是当我运行我的代码时 显然安装的软件包和两个版本 最新和 0 8 18 存在一些问题 由于我不知道如何解决
  • Android 开发人员 - 警报管理器与服务

    我正在制作一个应用程序 即使应用程序关闭 也需要每小时执行一个函数 首先 我想创建一个服务 但是在我的测试过程中 我意识到android有时会杀死我的服务 所以我正在寻找另一个解决方案 然后我找到了 AlarmManager 我已经实现了它
  • JSF2 和 PrettyFaces...如何获取原始 URL 或查询字符串?

    PrettyFaces 是一个极其简单的 URL 重写引擎 各种 SEO 都是可能的真的真的很容易 不过我有一个小问题 使用漂亮的面孔 我有这个重写规则
  • python 中的 Matplotlib.colors.ListedColormap

    def plot decision regions X y classifier resolution 0 02 setup marker generator and color map markers s x o v colors red
  • (Python) 如何让用户打开文本文件,然后更改整数/数字

    我曾问过类似的问题 但没有结果 我是一名编程新手 只教过一些基本技术 任务的一部分是创建一个食谱程序 我大部分时间都完成了这个程序 只有一个部分阻止我完成 我应该允许用户调用以前创建的文本文件 我已经完成了这一点 然后在此之后应该显示该文件