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_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)
|
||||
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())
|
||||
1
Semaine_04/Contacts/.python-version
Normal file
1
Semaine_04/Contacts/.python-version
Normal file
@@ -0,0 +1 @@
|
||||
3.12
|
||||
0
Semaine_04/Contacts/README.md
Normal file
0
Semaine_04/Contacts/README.md
Normal file
91
Semaine_04/Contacts/classes.py
Normal file
91
Semaine_04/Contacts/classes.py
Normal file
@@ -0,0 +1,91 @@
|
||||
import json
|
||||
|
||||
class Contact:
|
||||
def __init__(self, name: str, phone: str, email: str):
|
||||
self.name = name
|
||||
self.phone = phone
|
||||
self.email = email
|
||||
|
||||
def __iter__(self):
|
||||
yield self.name
|
||||
yield self.phone
|
||||
yield self.email
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"{self.name} - {self.phone} - {self.email}"
|
||||
|
||||
def __eq__(self, other: "Contact"):
|
||||
return self.name == other.name\
|
||||
and self.phone == other.phone\
|
||||
and self.email == other.email
|
||||
|
||||
def serialized(self):
|
||||
"""Converti la classe en dictionnaire JSONable"""
|
||||
return {"Name": self.name, "Phone": self.phone, "Email": self.email}
|
||||
|
||||
@classmethod
|
||||
def deserialized(cls, dictionnary):
|
||||
"""Lis un JSON pour le retranscrire en classe Contact"""
|
||||
return cls(name= dictionnary["Name"], phone= dictionnary["Phone"], email= dictionnary["Email"])
|
||||
|
||||
class Repertory:
|
||||
def __init__(self, name: str):
|
||||
self.name = name
|
||||
self.contacts: list[Contact] = self.load()
|
||||
|
||||
def __iter__(self):
|
||||
return iter(self.contacts)
|
||||
|
||||
def __getitem__(self, index: int) -> Contact:
|
||||
return self.contacts[index]
|
||||
|
||||
def add_contact(self, contact: Contact):
|
||||
if contact in self.contacts:
|
||||
return f"{contact.name} est déjà dans le répertoire."
|
||||
self.contacts.append(contact)
|
||||
self.save()
|
||||
return f"Nouveau contact :\nNom : {contact.name}\nNuméro : {contact.phone}\nCourriel : {contact.email}"
|
||||
|
||||
def delete_contact(self, contact_info: str):
|
||||
for contact in self.contacts:
|
||||
if contact.name.lower() == contact_info.lower()\
|
||||
or contact.phone.lower() == contact_info.lower()\
|
||||
or contact.email.lower() == contact_info.lower():
|
||||
self.contacts.remove(contact)
|
||||
self.save()
|
||||
return f"{contact.name} a été supprimé du répertoire."
|
||||
return f"{contact.name} n'est pas dans le répertoire."
|
||||
|
||||
def search_contact(self, research_str: str):
|
||||
results = []
|
||||
for contact in self.contacts:
|
||||
if research_str.lower() in contact.name.lower()\
|
||||
or research_str.lower() in contact.phone.lower()\
|
||||
or research_str.lower() in contact.email.lower():
|
||||
results.append(contact)
|
||||
return results if len(results) > 0 else "Pas de résultat."
|
||||
|
||||
def display_contacts(self):
|
||||
results = []
|
||||
for idx, contact in enumerate(self.contacts):
|
||||
results.append(
|
||||
f"----- Contact n°{idx + 1} -----\n"
|
||||
f"Nom : {contact.name}\n"
|
||||
f"Numéro : {contact.phone}\n"
|
||||
f"Courriel : {contact.email}\n"
|
||||
" "
|
||||
)
|
||||
return "".join(results) if results else "Aucun contact dans le répertoire."
|
||||
|
||||
# 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"""
|
||||
contact_dict = [contact.serialized() for contact in self.contacts]
|
||||
with open("contacts.json", "w") as json_file: # a pour append, w pour write
|
||||
json.dump(contact_dict, json_file, indent= 4)
|
||||
|
||||
def load(self) -> list[Contact]:
|
||||
"""Récupère le contenu d'un fichier JSON"""
|
||||
with open("contacts.json") as json_file:
|
||||
return json.load(json_file, object_hook= Contact.deserialized)
|
||||
27
Semaine_04/Contacts/contacts.json
Normal file
27
Semaine_04/Contacts/contacts.json
Normal file
@@ -0,0 +1,27 @@
|
||||
[
|
||||
{
|
||||
"Name": "Alberto",
|
||||
"Phone": "0612345678",
|
||||
"Email": "alberto@courriel.fr"
|
||||
},
|
||||
{
|
||||
"Name": "Alice",
|
||||
"Phone": "0123456789",
|
||||
"Email": "alice@gmail.com"
|
||||
},
|
||||
{
|
||||
"Name": "Alberto",
|
||||
"Phone": "0482764563",
|
||||
"Email": "kfjsbdfg@sdfgj.fr"
|
||||
},
|
||||
{
|
||||
"Name": "Giorgio",
|
||||
"Phone": "857398375493",
|
||||
"Email": "giorgio.armani@armagnac.it"
|
||||
},
|
||||
{
|
||||
"Name": "Fran\u00e7ois LE GUERAND",
|
||||
"Phone": "0145892367",
|
||||
"Email": "fr-le-g@gmail.fr"
|
||||
}
|
||||
]
|
||||
18
Semaine_04/Contacts/main.py
Normal file
18
Semaine_04/Contacts/main.py
Normal file
@@ -0,0 +1,18 @@
|
||||
from classes import Contact,Repertory
|
||||
|
||||
repertory = Repertory("Repertoire")
|
||||
|
||||
for i in range(1):
|
||||
new_contact_name = input("Nom > ")
|
||||
new_contact_phone = input("Numéro > ")
|
||||
new_contact_email = input("Courriel > ")
|
||||
|
||||
new_contact = Contact(new_contact_name, new_contact_phone, new_contact_email)
|
||||
new_contact_added = repertory.add_contact(new_contact)
|
||||
|
||||
print(new_contact_added)
|
||||
|
||||
search_criteria = input("Critères de recherche > ")
|
||||
print(repertory.search_contact(search_criteria))
|
||||
|
||||
print(repertory.display_contacts())
|
||||
7
Semaine_04/Contacts/pyproject.toml
Normal file
7
Semaine_04/Contacts/pyproject.toml
Normal file
@@ -0,0 +1,7 @@
|
||||
[project]
|
||||
name = "contacts"
|
||||
version = "0.1.0"
|
||||
description = "Add your description here"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.12"
|
||||
dependencies = []
|
||||
8
Semaine_04/Contacts/uv.lock
generated
Normal file
8
Semaine_04/Contacts/uv.lock
generated
Normal file
@@ -0,0 +1,8 @@
|
||||
version = 1
|
||||
revision = 3
|
||||
requires-python = ">=3.12"
|
||||
|
||||
[[package]]
|
||||
name = "contacts"
|
||||
version = "0.1.0"
|
||||
source = { virtual = "." }
|
||||
Reference in New Issue
Block a user