【问题标题】:Writing and Editing Files (Python)编写和编辑文件 (Python)
【发布时间】:2015-03-18 18:49:33
【问题描述】:

首先我要道歉,因为我是 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 教程的Reading and Writing Files 部分了吗?
  • 我不知道如何允许用户通过输入需要多少份来增加原始份量,因为默认份量在文本文件中。有谁知道如何做到这一点?我是文件处理新手,一直在研究,但无济于事。
  • 你可以将你的文件读入字典或列表,修改它并覆盖你现有的文件
  • 读取文件,解析内容,转换数字int/float(就像你在代码的最后一行所做的那样),使用*将数字相乘,然后将它们转换回来字符串并重写文件。关于 SO 上的任何这些步骤都有很多问题。
  • 解析内容?你能提供一个示例代码吗?

标签: python file-handling


【解决方案1】:

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

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

2) 在 Python 中真正使用您自己的函数,尤其是在传递您自己的参数时。您正在尝试制作的是一个很好的“modular programming”的完美示例,您是否会正确读取输入文件的函数,写入输出文件的函数,提示用户输入他们想要的编号的函数多个,以此类推。

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) [半高级] 基本的正则表达式(又名“正则表达式”)非常有助于构建您正在制作的内容。听起来您的输入文件将具有严格的、可预测的格式,因此可能不需要正则表达式。但是,如果您希望接受非标准配方输入文件,那么正则表达式将是一个很好的工具。虽然学习它可能有点困难或令人困惑,但有很多很好的教程和指南。我过去收藏的几个是Python CourseGoogle DevelopersDive 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()

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

【讨论】:

    【解决方案2】:

    因为我使用的是 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()
    

    【讨论】:

    • 谢谢!它可以工作,但是这部分代码有什么作用? with open(Choice_Exist + ".txt", "r+") as f: content = f.readlines() data_list = [word.replace("\n","") for word in content]
    • 它打开前一行输入的配方文本文件,并将每一行读入列表content。在此列表中,列表中的每个条目之后都有“换行符”(\n)。所以data_list 删除了所有这些不需要的\n 字符。
    • @Maxine123 如果我的代码有效,你能接受我的回答吗? :) (按绿色复选标记)提前致谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-19
    • 1970-01-01
    • 2011-10-29
    • 1970-01-01
    • 2022-12-15
    • 2021-02-26
    相关资源
    最近更新 更多