w3resource

Python - Code Snippet Manager


Code Snippet Manager:

Input values:
1. User interacts with the program by adding, editing, or deleting code snippets.
2. User provides information such as snippet title, language, description, and code itself.
3. User can also search for specific snippets based on keywords or filters.

Output value:
Visual representation of the program interface displaying stored code snippets, search results, and feedback on user actions.

Example:

Input values:
1. Add a new code snippet:
- User enters the snippet title, language, description, and code.
- User saves the snippet.
Output value:
Visual representation of the program interface displays the newly added code snippet in the list of snippets.
Input values:
2. Search for a snippet:
- User enters keywords or filters to search for specific snippets.
Output value:
Visual representation of the program interface displays search results matching the entered keywords or filters.
Input values:
3. Edit a code snippet:
- User selects a code snippet to edit.
- User modifies the snippet title, language, description, or code.
- User saves the changes.
Output value:
Visual representation of the program interface displays the edited code snippet with updated information.
Input values:
4. Delete a code snippet:
- User selects a code snippet to delete.
- User confirms deletion.
Output value:
Visual representation of the program interface that removes the deleted code snippet from the list of snippets.
Input values:
5. View a code snippet:
- User selects a code snippet to view its details and code.
Output value:
Visual representation of the program interface displays the details and code of the selected snippet.
Input values:
6. Add tags to a code snippet:
- User selects a code snippet to add tags.
- User enters tags for the snippet.
- User saves the tags.
Output value:
Visual representation of the program interface displays the added tags for the code snippet.
Input values:
7. Filter snippets by tags:
- User selects tags to filter snippets.
- User applies the selected tags.
Output value:
Visual representation of the program interface displays snippets filtered by selected tags.

Solution 1: Basic Console-Based Code Snippet Manager

This solution offers a simple text-based interface where users can interact with a code snippet manager to add, search, edit, delete, and view code snippets. The data is stored in memory during the runtime, meaning the snippets are lost when the program ends.

Code:

# Solution 1: Console-based Code Snippet Manager
# The program allows users to add, search, edit, and delete code snippets.

class Snippet:
    def __init__(self, title, language, description, code, tags=[]):
        self.title = title  # Title of the snippet
        self.language = language  # Programming language of the snippet
        self.description = description  # Brief description of the snippet
        self.code = code  # Code of the snippet
        self.tags = tags  # Tags for filtering snippets

    def __str__(self):
        # Returns a formatted string of snippet details
        return f"Title: {self.title}\nLanguage: {self.language}\nDescription: {self.description}\nTags: {', '.join(self.tags)}\nCode:\n{self.code}"

class SnippetManager:
    def __init__(self):
        self.snippets = []  # List to store code snippets

    def add_snippet(self):
        # Adds a new snippet
        title = input("Enter snippet title: ")
        language = input("Enter programming language: ")
        description = input("Enter snippet description: ")
        code = input("Enter code: ")
        tags = input("Enter tags (comma-separated): ").split(', ')
        snippet = Snippet(title, language, description, code, tags)
        self.snippets.append(snippet)
        print(f"Snippet '{title}' added successfully!")

    def search_snippet(self):
        # Searches for snippets by keyword in title or description
        keyword = input("Enter keyword to search: ").lower()
        results = [s for s in self.snippets if keyword in s.title.lower() or keyword in s.description.lower()]
        if results:
            for snippet in results:
                print(snippet)
                print('-' * 40)
        else:
            print(f"No snippets found for keyword: {keyword}")

    def edit_snippet(self):
        # Edits an existing snippet based on title
        title = input("Enter the title of the snippet to edit: ")
        for snippet in self.snippets:
            if snippet.title == title:
                snippet.language = input(f"Enter new programming language (current: {snippet.language}): ")
                snippet.description = input(f"Enter new description (current: {snippet.description}): ")
                snippet.code = input("Enter new code: ")
                snippet.tags = input(f"Enter new tags (comma-separated, current: {', '.join(snippet.tags)}): ").split(', ')
                print(f"Snippet '{title}' updated successfully!")
                return
        print(f"Snippet '{title}' not found!")

    def delete_snippet(self):
        # Deletes a snippet based on title
        title = input("Enter the title of the snippet to delete: ")
        self.snippets = [s for s in self.snippets if s.title != title]
        print(f"Snippet '{title}' deleted!")

    def view_snippet(self):
        # Views details of a snippet based on title
        title = input("Enter the title of the snippet to view: ")
        for snippet in self.snippets:
            if snippet.title == title:
                print(snippet)
                return
        print(f"Snippet '{title}' not found!")

    def run(self):
        # Runs the main loop of the Snippet Manager
        while True:
            print("\nCode Snippet Manager")
            print("1. Add Snippet")
            print("2. Search Snippet")
            print("3. Edit Snippet")
            print("4. Delete Snippet")
            print("5. View Snippet")
            print("6. Exit")

            choice = input("Choose an option: ")
            if choice == '1':
                self.add_snippet()
            elif choice == '2':
                self.search_snippet()
            elif choice == '3':
                self.edit_snippet()
            elif choice == '4':
                self.delete_snippet()
            elif choice == '5':
                self.view_snippet()
            elif choice == '6':
                print("Exiting Code Snippet Manager.")
                break
            else:
                print("Invalid option, try again.")

# Run the Snippet Manager
if __name__ == '__main__':
    manager = SnippetManager()
    manager.run()

Output:

 Code Snippet Manager
1. Add Snippet
2. Search Snippet
3. Edit Snippet
4. Delete Snippet
5. View Snippet
6. Exit
Choose an option: 1
Enter snippet title: Hangman Game
Enter programming language: Python
Enter snippet description: : Implement a hangman game where the computer selects words and the player guesses.
Enter code: # Solution 1: Basic Approach Using Functions and Loops

import random  # Import the random module to select a random word

# List of words for the Hangman game
word_list = ['python', 'hangman', 'programming', 'developer', 'algorithm']

def choose_word(word_list):
    """Randomly select a word from the word list."""
    return random.choice(word_list)

def display_current_state(word, guessed_letters):
    """Display the current state of the guessed word with correct letters revealed."""
    current_state = ''.join([letter if letter in guessed_letters else '_' for letter in word])
    return current_state
Enter tags (comma-separated): Python,Project
Snippet 'Hangman Game' added successfully!

Code Snippet Manager
1. Add Snippet
2. Search Snippet
3. Edit Snippet
4. Delete Snippet
5. View Snippet
6. Exit
Choose an option: 5
Enter the title of the snippet to view: Hangman Game
Title: Hangman Game
Language: Python
Description: Implement a hangman game where the computer selects words and the player guesses.
Tags: Python,Project
Code:
# Solution 1: Basic Approach Using Functions and Loops

import random  # Import the random module to select a random word

# List of words for the Hangman game
word_list = ['python', 'hangman', 'programming', 'developer', 'algorithm']

def choose_word(word_list):
    """Randomly select a word from the word list."""
    return random.choice(word_list)

def display_current_state(word, guessed_letters):
    """Display the current state of the guessed word with correct letters revealed."""
    current_state = ''.join([letter if letter in guessed_letters else '_' for letter in word])
    return current_state

Code Snippet Manager
1. Add Snippet
2. Search Snippet
3. Edit Snippet
4. Delete Snippet
5. View Snippet
6. Exit
Choose an option: 6
Exiting Code Snippet Manager.

Explanation:

  • Snippet Class: Represents a code snippet with attributes like title, language, description, code, and tags.
  • SnippetManager Class: Manages the operations like adding, editing, deleting, and searching code snippets.
  • User Operations:
    • Add a snippet (title, language, description, code, tags).
    • Search for snippets by keyword.
    • Edit or delete snippets by title.
    • View detailed snippet information.

Solution 2: GUI-Based Code Snippet Manager using Tkinter

This solution provides a graphical user interface (GUI) for users to add, view, search, and manage code snippets. The program uses the tkinter library for creating the interface.

Code:

import tkinter as tk
from tkinter import simpledialog, messagebox

class Snippet:
    def __init__(self, title, language, description, code, tags=[]):
        self.title = title
        self.language = language
        self.description = description
        self.code = code
        self.tags = tags

class SnippetManagerGUI:
    def __init__(self, root):
        self.snippets = []  # Stores all snippets
        self.root = root
        self.root.title("Code Snippet Manager")
        
        # Buttons
        self.add_button = tk.Button(root, text="Add Snippet", command=self.add_snippet)
        self.view_button = tk.Button(root, text="View Snippet", command=self.view_snippet)
        self.search_button = tk.Button(root, text="Search Snippet", command=self.search_snippet)
        self.delete_button = tk.Button(root, text="Delete Snippet", command=self.delete_snippet)
        
        # Layout
        self.add_button.pack(pady=5)
        self.view_button.pack(pady=5)
        self.search_button.pack(pady=5)
        self.delete_button.pack(pady=5)
        
    def add_snippet(self):
        # Adds a new snippet through dialog boxes
        title = simpledialog.askstring("Title", "Enter snippet title:")
        language = simpledialog.askstring("Language", "Enter programming language:")
        description = simpledialog.askstring("Description", "Enter snippet description:")
        code = simpledialog.askstring("Code", "Enter the code:")
        tags = simpledialog.askstring("Tags", "Enter tags (comma-separated):").split(', ')
        snippet = Snippet(title, language, description, code, tags)
        self.snippets.append(snippet)
        messagebox.showinfo("Success", f"Snippet '{title}' added successfully!")

    def view_snippet(self):
        # Views snippet based on title input
        title = simpledialog.askstring("Title", "Enter the title of the snippet to view:")
        for snippet in self.snippets:
            if snippet.title == title:
                snippet_info = f"Title: {snippet.title}\nLanguage: {snippet.language}\nDescription: {snippet.description}\nCode:\n{snippet.code}\nTags: {', '.join(snippet.tags)}"
                messagebox.showinfo("Snippet Details", snippet_info)
                return
        messagebox.showwarning("Error", f"Snippet '{title}' not found!")

    def search_snippet(self):
        # Searches for a snippet based on a keyword
        keyword = simpledialog.askstring("Search", "Enter keyword to search:")
        results = [s for s in self.snippets if keyword.lower() in s.title.lower() or keyword.lower() in s.description.lower()]
        if results:
            result_str = "\n".join([s.title for s in results])
            messagebox.showinfo("Search Results", f"Found snippets:\n{result_str}")
        else:
            messagebox.showwarning("No Results", f"No snippets found for keyword '{keyword}'.")

    def delete_snippet(self):
        # Deletes snippet based on title
        title = simpledialog.askstring("Delete", "Enter the title of the snippet to delete:")
        self.snippets = [s for s in self.snippets if s.title != title]
        messagebox.showinfo("Success", f"Snippet '{title}' deleted.")

# Run the GUI application
if __name__ == '__main__':
    root = tk.Tk()
    app = SnippetManagerGUI(root)
    root.mainloop()

Output:

Python: Code Snippet Manager.

Python: Snippet Details.

Explanation:

  • Snippet Class: Same as in Solution 1.
  • SnippetManagerGUI Class: Handles the GUI interface for the code snippet manager.
  • User Operations:
  • o
    • Add a snippet through dialog boxes.
    • Search for snippets using keywords.
    • View or delete snippets by title


Follow us on Facebook and Twitter for latest update.