简体   繁体   English

如何将数学方程式从函数写入文件?

[英]How to write math equation from function to a file?

I'm trying to stats from a file and calculate the mean,median,min and max. 我正在尝试从文件中统计数据并计算均值,中位数,最小值和最大值。 This much I've been able to do. 我已经能够做到这一点。

Where I'm struggling is I need to then give the user an option to save the computed stats to a new file. 我苦苦挣扎的地方是,然后需要给用户一个选项,以将计算的统计信息保存到新文件中。 It's giving me an error that's saying 'str' object has no attribute 'write' 它给我一个错误,说“ str”对象没有属性“ write”

Does anyone know how I could write my "computed_stats" function to a file? 有谁知道如何将我的“ computed_stats”函数写入文件? I'd really appreciate any help! 我真的很感谢您的帮助!

Here is a screen shot of the bulk of my code. 这是我的大部分代码的屏幕截图。 I didn't have enough screen space to include the table that prompts the user to enter selections or the function that loads data. 我没有足够的屏幕空间来包含表格,该表格提示用户输入选择或加载数据的功能。 They didn't seem important for this issue. 他们似乎对这个问题并不重要。

def table():
    print("Choose an option:")
    print("1. Load data")
    print("2. Display computed statistics")
    print("3. Save computed statistics")
    print("4. Exit")

def load_data(filename):
    with open(filename) as f:
        for lines in f:
            numbers = lines.split()
            return(numbers)

def compute_stats(data_list):

    minimum = (min(data_list))
    maximum = (max(data_list))
    mean = (sum(data_list) / (len(data_list)))
    data = sorted(data_list)
    if (len(data) % 2) == 1:
        median = data[len(data) // 2]      
    else:
        median = (data[len(data) // 2] + data[len(data) // 2 - 1]) / 2
    return minimum, maximum, mean, median

def print_stats(data_list):
    minumum, maximum, mean, median = compute_stats(data_list)
    print(minimum)
    print(maximum)
    print(mean)
    print(median)


def save_stats(new_file):
    global comp_data    
    with open(new_file, 'w') as f:        
        f.close()



def main():


    selection = 0
    while selection != "4":
        table()
        selection = input("Choose a selection: ")
        print()

        if selection == "1":
            data_list = input("Enter the name of your file: ")
            data_list = load_data(data_list)
            data_list = [int(x) for x in data_list]
            print("Data read sucessfully \n")


        elif selection == "2":          
            print_stats(data_list)


        elif selection == "3":
            new_file = input("Enter File Name")
            save_stats(new_file)


main()

One classical problem that you have here is that you have mixed up presentation of the results with the computation. 您在这里遇到的一个经典问题是您将结果的表示与计算混淆了。 In your code, the computed_stats function does both the printing and the computing. 在您的代码中, computed_stats函数可进行打印和计算。 By the way, it is badly named, something like print_statistics might be better. 顺便说一句,它的名字很糟糕,比如print_statistics可能更好。 Often, when your function names don't naturally start with a verb, their responsibilities are badly defined. 通常,当您的函数名称不是自然地以动词开头时,它们的职责就被错误地定义了。

For a very first change I would do something like this: 对于第一个更改,我将执行以下操作:

def compute_statistics(data_list):
    # Do whatever computations you need but don't print anything
    minimum = #Insert computation for minimum here
    maximum = #Insert computation for maximum here
    mean = #Insert computation for mean here
    median = #Insert computation for median here
    return minimum, maximum, mean, median # whatever statistics you are computing

def print_statistics(data_list):
    minimum, maximum, mean, median=compute_statistics(data_list)
    # Put your printing logic here using the results from above

def save_statistics(file_name, data_list):
    minimum, maximum, mean, median=compute_statistics(data_list)
    with open(file_name,'w') as outfile:
        file.write(f"min = {minimum}\n")
        # Put all your saving logic here

If you want the printed version to look exactly like the saved version, you might also add a function for generating that string, that you can call upon from print_statistics and save_statistics . 如果希望打印的版本看起来与保存的版本完全相同,则还可以添加一个用于生成该字符串的函数,可以从print_statisticssave_statistics调用该print_statistics

Later on, you might wish to think about how to better manage the state of your application so that you don't have to recompute statistics every time. 稍后,您可能希望考虑如何更好地管理应用程序的状态,以便不必每次都重新计算统计信息。 But that is a story for another time. 但这是另一个故事。

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

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