个人存档工具,寻找有关改进代码的建议

时间:2010-07-26 19:04:33

标签: python archive code-snippets

我在python中编写了一个工具,您可以在其中输入标题,内容和标签,然后将条目保存在pickle文件中。它主要是为复制粘贴功能而设计的(你在网上发现你喜欢的一段代码,复制它并将其粘贴到程序中),而不是手写内容,尽管它没有问题。

我主要是因为我总是在扫描我的pdf文件,书籍或网络,以寻找我之前已经看过的解决方案的一些编码示例,而且你可以放一些东西似乎合乎逻辑内容,给它一个标题和标签,并在需要时查看。

我意识到网上有网站处理这个前任。 http://snippets.dzone.com,但我在编码时并不总是在线。我也承认我并不是真的想看看是否有人写过桌面应用程序,这个项目在我这里做起来似乎很有趣。

它没有设计成数百万条目,所以我只使用pickle文件来序列化数据而不是其中一个数据库API。查询也非常基本,只有标题和标签,没有基于查询的排名。

有一个我无法弄清楚的问题,当你在条目列表中有一个try,except子句,它试图捕获一个有效的索引(整数)。如果输入inavlid整数,它将要求您输入一个有效的整数,但它似乎无法将其分配给变量。如果您直接输入有效的整数,则没有问题,并且将显示该条目。

无论如何让我知道你们的想法。这是为python3编码的。

主文件:

#!usr/bin/python

from archive_functions import Entry, choices, print_choice, entry_query 
import os

def main():
    choice = ''
    while choice != "5":
        os.system('clear')
        print("Mo's Archive, please select an option")
        print('====================')
        print('1. Enter an entry')
        print('2. Lookup an entry')
        print('3. Display all entries')
        print('4. Delete an entry')
        print('5. Quit')
        print('====================')
        choice = input(':')

        if choice == "1":
            entry = Entry()
            entry.get_data()
            entry.save_data()

        elif choice == "2":
            queryset = input('Enter title or tag query: ') 
            result = entry_query('entry.pickle', queryset)
            if result:
                print_choice(result, choices(result))
            else:
                os.system('clear')
                print('No Match! Please try another query')
                pause = input('\npress [Enter] to continue...')

        elif choice == "3":
            queryset = 'all'    
            result = entry_query('entry.pickle', queryset)
            if result:
                print_choice(result, choices(result))

        elif choice == "4":
            queryset = input('Enter title or tag query: ')
            result = entry_query('entry.pickle', queryset)
            if result:
                entry = result[choices(result)]
                entry.del_data()
            else:
                os.system('clear')
                print('No Match! Please try another query')
                pause = input('\npress [Enter] to continue...')

        elif choice == "5":
            break

        else:
            input('please enter a valid choice...')
            main()

if __name__ == "__main__":
    main()

archive_functions.py:

#!/bin/usr/python
import sys
import pickle
import os
import re

class Entry():
    def get_data(self):
        self.title = input('enter a title: ')
        print('enter the code, press ctrl-d to end: ')
        self.code = sys.stdin.readlines()
        self.tags = input('enter tags: ')

    def save_data(self):
        with open('entry.pickle', 'ab') as f:
            pickle.dump(self, f)

    def del_data(self):
        with open('entry.pickle', 'rb') as f:
            data_list = []
            while True:
                try:
                    entry = pickle.load(f)
                    if self.title == entry.title:
                        continue
                    data_list.append(entry)
                except:
                    break
        with open('entry.pickle', 'wb') as f:
            pass
        with open('entry.pickle', 'ab') as f:
            for data in data_list:
                data.save_data()

def entry_query(file, queryset):
    '''returns a list of objects matching the query'''
    result = []
    try:
        with open(file, 'rb') as f:
           entry = pickle.load(f)
           os.system('clear')
           if queryset == "all":
               while True:
                   try:
                       result.append(entry)
                       entry = pickle.load(f)
                   except:
                       return result
                       break
           while True:
                try:
                    if re.search(queryset, entry.title) or re.search(queryset, entry.tags):
                        result.append(entry)
                        entry = pickle.load(f)
                    else:
                        entry = pickle.load(f)
                except:
                    return result
                    break
    except:
        print('no entries in file, please enter an entry first')
        pause = input('\nPress [Enter] to continue...')

def choices(list_result):
    '''takes a list of objects and returns the index of the selected object'''
    os.system('clear')
    index = 0
    for entry in list_result:
        print('{}. {}'.format(index, entry.title))
        index += 1
    try:
        choice = int(input('\nEnter choice: '))
        return choice
    except:
        pause = input('\nplease enter a valid choice')
        choices(list_result)


def print_choice(list_result, choice):
    '''takes a list of objects and an index and displays the index of the list'''
    os.system('clear')
    print('===================')
    print(list_result[choice].title)
    print('===================')
    for line in list_result[choice].code:
       print(line, end="")
    print('\n\n')
    back_to_choices(list_result)

def back_to_choices(list_result):
    print('1. Back to entry list')
    print('2. Back to Main Menu')
    choice = input(':')
    if choice == "1":
        print_choice(list_result, choices(list_result))
    elif choice == "2":
        pass
    else:
        print('\nplease enter a valid choice')
        back_to_choices(list_result)

1 个答案:

答案 0 :(得分:1)

else中,您再次递归调用main函数。相反,我会做choice == "0"之类的事情,这只会导致while循环请求另一个条目。这避免了无意义的递归。