Solution officielle
import re
import math
from collections import Counter, defaultdict
def tokeniser(texte):
mots = re.findall(r'[a-zA-ZÀ-ÿ0-9]+', texte.lower())
return [mot for mot in mots if len(mot) > 1]
class MoteurRecherche:
def __init__(self):
self.documents = []
self.idf = {}
def _calculer_idf(self):
N = len(self.documents)
if N == 0:
return {}
df = defaultdict(int)
for doc in self.documents:
for mot in set(tokeniser(doc)):
df[mot] += 1
return {mot: math.log(N / freq) for mot, freq in df.items()}
def ajouter_document(self, texte):
self.documents.append(texte)
self.idf = self._calculer_idf()
def _scorer(self, document, requête):
mots = tokeniser(document)
if not mots:
return 0.0
total = len(mots)
compteur = Counter(mots)
tf = {mot: count / total for mot, count in compteur.items()}
return sum(tf.get(mot, 0) * self.idf.get(mot, 0) for mot in tokeniser(requête))
def rechercher(self, requête, top_n=5):
résultats = []
for i, doc in enumerate(self.documents):
score = self._scorer(doc, requête)
if score > 0:
extrait = doc[:50]
résultats.append((i, score, extrait))
résultats.sort(key=lambda x: x[1], reverse=True)
return résultats[:top_n]