Semaine 4, jour 3, soir
This commit is contained in:
22
Semaine_04/Bibliotheque/books.json
Normal file
22
Semaine_04/Bibliotheque/books.json
Normal file
@@ -0,0 +1,22 @@
|
||||
[
|
||||
{
|
||||
"Title": "LSDA",
|
||||
"Author": "Tolkien"
|
||||
},
|
||||
{
|
||||
"Title": "1984",
|
||||
"Author": "Orwell"
|
||||
},
|
||||
{
|
||||
"Title": "Pens\u00e9es pour moi-m\u00eame",
|
||||
"Author": "Marc Aur\u00e8le"
|
||||
},
|
||||
{
|
||||
"Title": "La voie des rois",
|
||||
"Author": "Brendan Sanderson"
|
||||
},
|
||||
{
|
||||
"Title": "Justici\u00e8re",
|
||||
"Author": "Brendan Sanderson"
|
||||
}
|
||||
]
|
||||
92
Semaine_04/Bibliotheque/classes.py
Normal file
92
Semaine_04/Bibliotheque/classes.py
Normal file
@@ -0,0 +1,92 @@
|
||||
import json
|
||||
|
||||
class Book:
|
||||
def __init__(self, title: str, author: str):
|
||||
self.title = title
|
||||
self.author = author
|
||||
|
||||
def __repr__(self):
|
||||
return f"{self.title} de {self.author}"
|
||||
|
||||
def __eq__(self, other: "Book"):
|
||||
"""Pour comparer un objet de classe à un autre au lieu de l'ID par défaut"""
|
||||
return self.title == other.title and self.author == other.author
|
||||
|
||||
def __gt__(self, other: "Book"):
|
||||
return self.title > other.title
|
||||
|
||||
def __lt__(self, other: "Book"):
|
||||
return self.title.lower() < other.title.lower()
|
||||
|
||||
def serialized(self):
|
||||
"""Converti la classe en dictionnaire JSONable"""
|
||||
return {"Title": self.title, "Author": self.author}
|
||||
|
||||
@classmethod
|
||||
def deserialized(cls, dictionnary):
|
||||
"""Lis un JSON pour le retranscrire en classe Book"""
|
||||
return cls(title= dictionnary["Title"], author= dictionnary["Author"])
|
||||
|
||||
class Library:
|
||||
"""Gère un contenu de livres"""
|
||||
def __init__(self, name: str):
|
||||
self.name = name
|
||||
self.books = self.load()
|
||||
|
||||
def add_new_book(self, book: Book):
|
||||
"""Ajoute un nouveau livre"""
|
||||
if book in self.books:
|
||||
return f"{book.title.capitalize()} y est déjà."
|
||||
self.books.append(book)
|
||||
self.save()
|
||||
return f"{book.title.capitalize()} a été ajouté."
|
||||
|
||||
def take_out_book(self, book_name: str):
|
||||
"""Retire un livre déjà présent"""
|
||||
for book in self.books:
|
||||
if book.title.lower() == book_name.lower():
|
||||
self.books.remove(book)
|
||||
self.save()
|
||||
return f"{book.title.capitalize()} a été retiré."
|
||||
return f"{book.title.capitalize()} n'y est pas."
|
||||
|
||||
def list_books_in_list(self):
|
||||
"""Liste les livres présents"""
|
||||
return self.books
|
||||
|
||||
def sort_books_by_name(self):
|
||||
"""Tri les livres par ordre alphabétique"""
|
||||
self.books.sort()
|
||||
|
||||
def display_number_of_books(self) -> int:
|
||||
"""Donne le nombre de livres présents"""
|
||||
return len(self.books)
|
||||
|
||||
def search_book_by_word(self, word: str):
|
||||
"""Cherche un livre par mot de départ"""
|
||||
results = []
|
||||
for book in self.books:
|
||||
if word.lower() in book.title.lower():
|
||||
results.append(book)
|
||||
return results if len(results) > 0 else "Pas de résultat."
|
||||
|
||||
def search_book_by_letter(self, letter: str):
|
||||
"""Cherche un livre par lettre de départ"""
|
||||
results = []
|
||||
for book in self.books:
|
||||
if book.title.lower().startswith(letter):
|
||||
results.append(book)
|
||||
return results if len(results) > 0 else "Pas de résultat."
|
||||
|
||||
# Sauvegarde des livres dans un JSON pour persistance des données
|
||||
|
||||
def save(self):
|
||||
"""Inscris dans un fichier JSON le contenu de la bibliothèque"""
|
||||
book_dict = [book.serialized() for book in self.books]
|
||||
with open("books.json", "w", encoding= "utf-8") as json_file: # a pour append, w pour write
|
||||
json.dump(book_dict, json_file, indent= 4)
|
||||
|
||||
def load(self) -> list[Book]:
|
||||
"""Récupère le contenu d'un fichier JSON"""
|
||||
with open("books.json", encoding= "utf-8") as json_file:
|
||||
return json.load(json_file, object_hook= Book.deserialized)
|
||||
@@ -1,58 +0,0 @@
|
||||
import json
|
||||
|
||||
def add_new_book(book_list: list[dict[str, str]], book: dict[str, str]): # On précise le contenu des clefs et valeurs du dictionnaire
|
||||
"""Ajoute un nouveau livre"""
|
||||
if book in book_list:
|
||||
return f"{book["Title"].upper()} y est déjà."
|
||||
book_list.append(book)
|
||||
save(book_list)
|
||||
return f"{book["Title"].upper()} a été ajouté."
|
||||
|
||||
def take_out_book(book_list: list[dict[str, str]], title: str):
|
||||
"""Retire un livre déjà présent"""
|
||||
for book in book_list:
|
||||
if book["Title"].lower() == title.lower():
|
||||
book_list.remove(book)
|
||||
save(book_list)
|
||||
return f"{title.upper()} a été retiré."
|
||||
return f"{title.upper()} n'y est pas."
|
||||
|
||||
def list_books_in_list(book_list: list[dict]):
|
||||
"""Liste les livres présents"""
|
||||
return book_list
|
||||
|
||||
def sort_books_by_name(book_list: list[dict]):
|
||||
"""Tri les livres par ordre alphabétique"""
|
||||
book_list.sort(key= lambda dict: dict["Title"]) # pour trier par clefs et non plus par objets
|
||||
|
||||
def display_number_of_books(book_list: list) -> int:
|
||||
"""Donne le nombre de livres présents"""
|
||||
return len(book_list)
|
||||
|
||||
def search_book_by_word(book_list: list[dict[str, str]], word: str):
|
||||
"""Cherche un livre par mot de départ"""
|
||||
results = []
|
||||
for book in book_list:
|
||||
if word.lower() in book["Title"].lower():
|
||||
results.append(book)
|
||||
return results if len(results) > 0 else "Pas de résultat."
|
||||
|
||||
def search_book_by_letter(book_list: list[dict[str, str]], letter: str):
|
||||
"""Cherche un livre par lettre de départ"""
|
||||
results = []
|
||||
for book in book_list:
|
||||
if book["Title"].lower().startswith(letter):
|
||||
results.append(book)
|
||||
return results if len(results) > 0 else "Pas de résultat."
|
||||
|
||||
# Sauvegarde des livres dans un JSON pour persistance des données
|
||||
|
||||
def save(book_list):
|
||||
"""Inscris dans un fichier JSON le contenu de la bibliothèque"""
|
||||
with open("books.json", "w") as json_file:
|
||||
json.dump(book_list, json_file, indent= 4)
|
||||
|
||||
def load():
|
||||
"""Récupère le contenu d'un fichier JSON"""
|
||||
with open("books.json") as json_file:
|
||||
return json.load(json_file)
|
||||
@@ -1,36 +1,16 @@
|
||||
from functions import \
|
||||
add_new_book,\
|
||||
take_out_book,\
|
||||
list_books_in_list,\
|
||||
sort_books_by_name,\
|
||||
display_number_of_books,\
|
||||
search_book_by_word,\
|
||||
search_book_by_letter,\
|
||||
save, load
|
||||
from classes import Book, Library
|
||||
|
||||
books = []
|
||||
library = Library("Romans")
|
||||
|
||||
for i in range(3):
|
||||
new_book_title = input ("Quel livre ajouter ? > ")
|
||||
new_book_title = input ("Quel livre ajouter ? > ")
|
||||
new_book_author = input ("Qui l'a écrit ? > ")
|
||||
new_book = {
|
||||
"Title": new_book_title,
|
||||
"Author": new_book_author
|
||||
}
|
||||
new_book_added = add_new_book(books, new_book)
|
||||
print (new_book_added)
|
||||
new_book = Book(new_book_title, new_book_author)
|
||||
new_book_added = library.add_new_book(new_book)
|
||||
print(new_book_added)
|
||||
|
||||
#print(take_out_book(books, new_book))
|
||||
print(library.list_books_in_list())
|
||||
|
||||
sort_books_by_name(books)
|
||||
print(list_books_in_list(books))
|
||||
library.sort_books_by_name()
|
||||
|
||||
book_number = display_number_of_books(books)
|
||||
|
||||
print(f"La bibliothèque contient {book_number} livres.")
|
||||
|
||||
searching_word = input("Mot recherché > ")
|
||||
print(search_book_by_word(books, searching_word))
|
||||
|
||||
searching_letter = input("Lettre recherchée > ")
|
||||
print(search_book_by_letter(books, searching_letter))
|
||||
print(library.list_books_in_list())
|
||||
Reference in New Issue
Block a user