【问题标题】:how to load a file as a list and place it in a different class to the one its loading in如何将文件加载为列表并将其放置在与其加载的类不同的类中
【发布时间】:2012-05-27 04:04:25
【问题描述】:
class Tasks(object):
    def __init__(self, container=None):
        if container is None:
            container = []
        self.container = container


    def add(self,name,date,priority):
        self.container.append([name,date,priority])

    def __str__(self):
        return str(self.container)

    def __repr__(self):
        return str(self.container)

    def __getitem__(self, key):
        return Tasks(self.container[key])

    def __len__(self):
        return len(self.container)


class management(Tasks):
    def save(self):
        outfile = open ("tasks.txt","w")
        outfile.write(("\n".join(map(lambda x: str(x), task))))

        print task
        outfile.close ()
    def load(self):
        load_file = open("tasks.txt","r")
        task = load_file.readlines()
        print task
        #this line is the attempt to convert back into the original format
        Tasks(add(task))




task = Tasks()        
if __name__== "__main__":

    p = management(Tasks)

    #task.add("birthday","27092012","high")
    #task.add("christmas","20062000","medium")
    #task.add("easter","26011992","low")
    print task

    #print len(task)
    #p.save()
    p.load()


    print "test",task
    print len(task)

我的代码的最终目的是生成一个任务管理器(待办事项列表)

上面的代码生成一个 [name,date,priority] 列表,然后将其保存在一个名为 tasks.txt 的文本文件中——据我所知,这可以完美运行(只要我注释掉 p.load) .

然而...... load 函数会加载文件,但我需要能够打印它作为打印任务加载的列表,就像我在注释掉 p.load() 时所做的那样。

这将使我能够最终完成、删除、排序等任务

提前致谢

对于我不知道如何在一行上表达的糟糕问题,我深表歉意

编辑: 我考虑过酸洗可以保留列表格式,但我认为它不能解决我能够将参数传递回 Tasks() 类以便能够将它们打印为打印任务的问题

编辑 2 load 函数现在读取

 def load(self):
     with open("tasks.txt", "r") as load_file:
         tasks = [ast.literal_eval(ln) for ln in load_file]
     print tasks
     for t in tasks:
         todo.add(t)

显然(或者至少我认为)我收到错误 NameError: global name 'todo' is not defined 我已经尝试使用 task.add(t) 并得到 TypeError: add() 需要 4 个参数(给定 2 个)

我也尝试使用 Tasks.add(t) 并得到错误 TypeError: unbound method add() must be called with Tasks instance as first argument (得到列表实例)

我显然不明白代码,你能解释一下吗,谢谢。

编辑 3 而真: menu_choice = int(input("从菜单中选择一个数字"))

try:
    if menu_choice == 1:

        task = raw_input ("task")
        date = raw_input ("date")
        priority = raw_input ("priority")
        tasks = Tasks([(task,date,priority)])
        print tasks


    elif menu_choice == 2:
        print tasks
    elif menu_choice == 3:
        tasks.save()
    elif menu_choice == 4:
        tasks.load()
except:
    print sys.exc_info()

这每次都会重写任务而不是附加它,有什么想法吗?菜单选项 2,3,4 也不起作用,因为任务不是全局定义的,不知道如何解决这个问题?也许回来?

【问题讨论】:

    标签: python list class function load


    【解决方案1】:

    假设您的名称、任务和优先级是简单的 Python 对象,您可以使用 ast.literal_eval 加载它们:

    with open("tasks.txt", "r") as load_file:
        # no need for readlines, just loop over the file!
        tasks = [ast.literal_eval(ln) for ln in load_file]
    

    然后循环tasks 将其中的对象放入Tasks 对象中。请注意,Tasks(add(task)) 不起作用。您需要有一个Tasks 类型的对象,将其传递给load(我们称之为todo),然后执行

    for t in tasks:
        todo.add(t)
    

    顺便说一句,您不需要 management 类。两个独立的功能就可以了。 Python is not Java.

    【讨论】:

    • 我不太明白,请您阅读“编辑 2”并澄清一下
    • ps 现在管理类仍然存在,但这篇文章读起来很有趣,我从来没有用 java 编码,因为 python 是我学习的第一门语言,一旦我能得到,我将完成 1/2 年这个程序完成了。谢谢你
    • @Street:您应该将todo 作为参数传递给load
    【解决方案2】:

    尝试不同的、更 Pythonic 的方法。与其说是答案,不如说是另一种选择。编辑三次以考虑对新功能的许多请求。

    import pickle
    
    class TasksError(Exception):
        def __init__(self, value):
            self.value = value
        def __str__(self):
            return repr(self.value)
    
    class Task(object):
        def __init__(self, task = () ):
            if task ==():
                raise TasksError('Empty task.')
            self.name = task[0]
            self.date = task[1]
            self.priority = task[2]
    
        def __str__(self):
            output = '''Name: %s
    Date: %s
    Priority: %s
    ''' % ( self.name,
            self.date,
            self.priority )
            return output
    
    class Tasks(object):
        def __init__(self, container = []):
            self.container = [ Task(todo) for todo in container ]
    
        def find_by_priority(self, priority = 'high'):
            # example method to seek and print high priority tasks
            # using this example, you will be able to conduct many
            # types of searches
            results = [ task
                       for task in self.container
                       if task.priority == priority ]
            return results
    
        def sort_by_date(self):
            # example method of how to sort, again, many other
            # ways of sorting can be implemented, this is just
            # to demonstrate the principle
            # for more info on sorting,
            # visit:  http://wiki.python.org/moin/HowTo/Sorting
            self.container = sorted(self.container,
                                    key=lambda task: task.date)
    
        def add(self, task):
            if task == '':
                raise TasksError('Empty task')
            self.container.append( Task(task) )
    
        def save(self):
            try:
                output = open('tasks.pkl', 'wb')
                pickle.dump(self.container, output)
                output.close()
            except:
                raise TasksError('Failed to save.')
    
        def load(self):
            try:
                pkl_file = open('tasks.pkl', 'rb')
                self.container = pickle.load(pkl_file)
                pkl_file.close()
            except:
                raise TasksError('Failed to load')
    
        def __str__(self):
            output = '\n'.join( [ str(todo) for todo in self.container ] )
            return output
    
    if __name__== "__main__":
        divider = '-' * 30 + '\n'
    
        tasks = Tasks( [("birthday","20121111","high"),
                        ("christmas","20121225","medium"),
                        ("easter","20120405","low")] )
        print 'Three original tasks:\n'
        print tasks # prints out three tasks
        print divider
    
        tasks.add( ("new-task","20120320","high") )
        print 'Three original plus one new task:\n'
        print tasks # prints out four tasks
        print divider
    
        tasks.save() # pickles the task list and saves to disk
    
        tasks = Tasks( container = [] ) # creates a new, empty task list
        print 'Empty task list:\n'
        print tasks # prints out empty list
        print divider
    
        tasks.load() # loads the pickled list
        print 'The four pickled tasks, reloaded:\n'
        print tasks # prints out four tasks
        print divider
    
        while True:
            print divider, '''Make your selection:
    1. Add new task
    2. Print all tasks
    3. Save tasks
    4. Load tasks from disk
    5. Find high priority tasks
    6. Sort by date
    <ENTER> to quit
    '''
            try:
                menu_choice = int(input("Select a number from the menu: "))
            except:
                print 'Goodbye!'
                break
    
            if menu_choice == 1:
                # note: no error checking here
                # even an empty input is accepted
                task = raw_input (">>> Task: ")
                date = raw_input (">>> Date as string YYYYMMDD: ")
                priority = raw_input (">>> Priority: ")
                todo = (task, date, priority)
                # note that here you should add a task
                # your method created a NEW task list
                # and replaced the old one
                tasks.add( todo )
                print tasks
            elif menu_choice == 2:
                print divider, 'Printing all tasks'
                print tasks
            elif menu_choice == 3:
                print divider, 'Saving all tasks'
                tasks.save()
            elif menu_choice == 4:
                print divider, 'Loading tasks from disk'
                tasks.load()
            elif menu_choice == 5:
                print divider, 'Finding tasks by priority'
                results = tasks.find_by_priority(priority='high')
                for result in results: print result
            elif menu_choice == 6:
                print divider, 'Sorting by date'
                tasks.sort_by_date()
                print tasks
    

    重要提示:这是作为练习生成的代码,用于演示您正在寻求实现的许多功能,并展示正确使用面向对象设计如何允许您封装每个任务和任务列表并操作它们轻松。它还演示了使用 pickle 作为您在原始问题中使用的文本文件实现的 Pythonic 替代方案。它还演示了按字段搜索和排序,实现了两个简单的方法。

    如果您对这个项目很认真,您需要查看一个合适的数据库,例如SQLite,它允许人们搜索、排序、更新、添加和删除记录的功能比您手动可靠地实现的要多。

    【讨论】:

    • 我尝试从您的代码创建用户输入菜单,但是任务会相互覆盖而不是附加,我将在上面的编辑 3 中发布代码,您能看看吗?谢谢!
    • 谢谢,我如何以列表格式访问每个任务,我需要能够从列表中删除任务(并对它们进行排序),我能看到的唯一列表是容器,它是一个局部变量,所以我不能用那个。不知道还能尝试什么?
    • 感谢您的代码,我注意到您删除的评论。非常感谢您的帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-22
    • 1970-01-01
    • 1970-01-01
    • 2021-11-11
    相关资源
    最近更新 更多