python - 编写和编辑文件 (Python)

标签 python file-handling

首先我想道歉,因为我是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's file I/O 。 1.a) 尝试重新创建您找到的示例,以确保您理解每段代码的作用。 1.b) 编写您自己的脚本来完成您想要的程序的这一部分,即打开现有的配方文本文件或创建一个新的文件。

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

3) 添加用于用户输入的 try/except block 。如果用户输入非数字值,您将能够捕获该值并再次提示用户输入更正的值。像这样的东西:

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) [半高级] 基本正则表达式(又名“正则表达式”)对于构建您正在制作的内容将非常有帮助。听起来您的输入文件将具有严格的、可预测的格式,因此可能不需要正则表达式。但如果您希望接受非标准配方输入文件,正则表达式将是一个很好的工具。虽然学习这项技能可能有点困难或令人困惑,但有很多很好的教程和指南。我过去加过书签的一些是 Python Course , Google Developers ,和 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 - 编写和编辑文件 (Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29130328/

相关文章:

python - Pandas 使用除法按聚合分组

python - Xerces + Python?

python - django - 如何在不覆盖原始条目的情况下保存修改后的表单

php - 从 php 调用 python 有 2 个返回值

python - 检查空格是否在字符串中

linux - Bash 脚本为不同的用户返回不同的结果

C++ 类,与不同用户一起处理一个文件

c - 从文件中读入变量

python - 如果在 json 转储期间抛出异常,如何避免部分文件?

python - 使用python处理和创建外部软件的输入文件