编写和编辑文件 (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 "))

我不得不编辑几次因为我使用 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()

我建议将您的工作分成多个步骤,并连续进行每个步骤(进行研究、尝试编写代码、提出具体问题)。

1) 查找python's file I/O。 1.a) 尝试重新创建您找到的示例,以确保您了解每段代码的作用。 1.b) 编写您自己的脚本来完成您想要的程序的这一部分,即打开一个现有的配方文本文件或创建一个新的。

2) 在 Python 中真正使用您自己的函数,尤其是在传递您自己的参数时。你想要做的是一个很好的例子“modular programming”,你是否会正确地读取输入文件的函数,另一个写入输出文件的函数,另一个提示用户他们编号的函数喜欢多,等等。

3) 为用户输入添加一个try/except块。如果用户输入 non-numeric 值,这将允许您捕获该值并再次提示用户输入更正的值。类似于:

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")将 非常 有助于构建您正在制作的内容。听起来您的输入文件将具有严格的、可预测的格式,因此可能不需要正则表达式。但是,如果您希望接受 non-standard 配方输入文件,正则表达式将是一个很好的工具。虽然学习起来可能有点困难或令人困惑,但有很多很好的教程和指南。我过去收藏的一些是 Python Course, Google Developers, and Dive Into Python. And a fantastic tool I strongly recommend while learning to build your own regular expression patterns is RegExr (or one of many similar, like 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()

开始可能会很艰难,但最终非常值得!祝你好运!