个人归档工具,寻找改进代码的建议

发布于 2024-09-12 00:49:05 字数 5676 浏览 2 评论 0原文

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

我这样做主要是因为我总是浏览我的pdf文件、书籍或网络,寻找一些我以前见过的解决方案的编码示例,并且有一些可以将内容放入其中的东西似乎是合乎逻辑的,给它一个标题和标签,然后在需要时查找它。

我意识到网上有一些网站可以处理这个前任。 http://snippets.dzone.com,但我编码时并不总是在线。我还承认,我并没有真正想看看是否有人编写了桌面应用程序,该项目似乎是一件有趣的事情,所以我在这里。

它在设计时并未考虑到数百万个条目,因此我只使用 pickle 文件来序列化数据,而不是使用数据库 API 之一。查询也非常基本,只有标题和标签,没有基于查询的排名。

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

无论如何,让我知道你们的想法。这是为 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)

i've written a tool in python where you enter a title, content, then tags, and the entry is then saved in a pickle file. it was mainly designed for copy-paste functionality (you spot a piece of code you like on the net, copy it, and paste it into the program), not really for handwritten content, though it does that with no problem.

i mainly did it because i'm always scanning through my pdf files, books, or the net for some coding example of solution that i'd already seen before, and it just seemed logical to have something where you could just put the content in, give it a title and tags, and just look it up whenever you needed to.

i realize there are sites online that handle this ex. http://snippets.dzone.com, but i'm not always online when i code. i also admit that i didn't really look to see if anyone had written a desktop app, the project seemed like a fun thing to do so here i am.

it wasn't designed with millions of entries in mind, so i just use a pickle file to serialize the data instead of one of the database APIs. the query is also very basic, only title and tags and no ranking based on the query.

there is an issue that i can't figure out, when you are at the list of entries there's a try, except clause where it tries to catch a valid index (integer). if you enter an inavlid integer, it will ask you to enter a valid one, but it doesn't seem to be able to assign it to the variable. if you enter a valid integer straightaway, there are no problems and the entry will display.

anyway let me know what you guys think. this is coded for python3.

main file:

#!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)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

貪欢 2024-09-19 00:49:05

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

In the else, you call the main function again recursively. Instead, I'd do something like choice == "0", which will just cause the while loop to request another entry. This avoids a pointless recursion.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文