繁体   English   中英

编写和编辑文件(Python)

[英]Writing and Editing Files (Python)

首先,我要道歉,因为我是Python的初学者。 无论如何,我有一个Python程序,可以在其中创建具有一般形式的文本文件:

Recipe Name:
Item
Weight
Number of people recipe serves

而我想做的就是让程序能够检索配方并为不同数量的人重新计算成分。 程序应输出配方名称,新人数和针对新人数的修订数量。 我能够检索配方并输出配方,但是我不确定如何为不同数量的人重新调配配料。 这是我的代码的一部分:

def modify_recipe():
    Choice_Exist = input("\nOkaym it looks like you want to modify a recipe. Please enter the name of this recipe ")
    Exist_Recipe = open(Choice_Exist, "r+")
    time.sleep(2)
    ServRequire = int(input("Please enter how many servings you would like "))

我建议将您的工作分成多个步骤,并依次进行每个步骤(进行研究,尝试编写代码,询问特定问题)。

1)查找python的文件I / O。 1.a)尝试重新创建发现的示例,以确保您了解每段代码的作用。 1.B)编写自己的脚本,完成只是这一块你想要的程序,即打开一个存在的配方文本文件或创建一个新的。

2)真正在Python中使用自己的函数,尤其是传递自己的参数时。 您要制作的是一个很好的“ 模块化编程 ”的完美示例,您是否可以对一个函数进行读取输入文件,另一个写入输出文件的功能,另一个提示用户编号的函数,例如: , 等等。

3)添加一个try/except块供用户输入。 如果用户输入非数字值,这将使您能够捕获该值并再次提示用户输入更正的值。 就像是:

while True:
  servings = raw_input('Please enter the number of servings desired: ')
  try:
    svgs = int(servings)
    break
  except ValueError:
    print('Please check to make sure you entered a numeric value, with no'
        +' letters or words, and a whole integer (no decimals or fractions).')

或者,如果要允许小数,可以使用float()而不是int()

4)[Semi-Advanced]基本正则表达式(又称“ regex”)对建立您正在做的工作非常有帮助。 听起来您的输入文件将具有严格的,可预测的格式,因此正则表达式可能不是必需的。 但是,如果您希望接受非标准的配方输入文件,则正则表达式将是一个很好的工具。 虽然学习起来可能有些困难或混乱,但是这里有很多很好的教程和指南。 我过去收藏过的一些软件包括Python课程Google开发人员Dive Into Python 在学习构建自己的正则表达式模式时,我强烈建议您使用一个出色的工具RegExr (或类似的类似工具之一,如PythonRegex ),它向您显示模式的哪些部分有效或无效以及原因。

以下是帮助您入门的概述:

def read_recipe_default(filename):
  # open the file that contains the default ingredients

def parse_recipe(recipe):
  # Use your regex to search for amounts here. Some useful basics include 
  # '\d' for numbers, and looking for keywords like 'cups', 'tbsp', etc.

def get_multiplier():
  # prompt user for their multiplier here

def main():
  # Call these methods as needed here. This will be the first part 
  #  of your program that runs.
  filename = ...
  file_contents = read_recipe_file(filename)
  # ...

# This last piece is what tells Python to start with the main() function above.
if __name__ == '__main__':
  main()

起步可能很艰难,但最终还是值得的! 祝好运!

我必须编辑几次,因为我使用的是Python 2.7.5,但这应该可以工作:

import time

def modify_recipe():
    Choice_Exist = input("\nOkay it looks like you want to modify a recipe. Please enter the name of this recipe: ")
    with open(Choice_Exist + ".txt", "r+") as f:
        content = f.readlines()
        data_list = [word.replace("\n","") for word in content]

    time.sleep(2)

    ServRequire = int(input("Please enter how many servings you would like: "))

    print data_list[0]
    print data_list[1]
    print int(data_list[2])*ServRequire #provided the Weight is in line 3 of txt file
    print ServRequire

modify_recipe()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM