Intermédiaire
🧠 Fondamentaux
20 XP
0 personnes ont réussi
Calcul TF (Term Frequency)
Quatrieme étape : mesurer l'importance d'un mot dans un document avec le TF (Term Frequency).
Le TF, c'est simplement le nombre de fois qu'un mot apparait dans un document, divise par le nombre total de mots du document. Ca normalise la frequence : un mot qui apparait 5 fois dans un document de 10 mots est plus important qu'un mot qui apparait 5 fois dans un document de 1000 mots.
Formule : TF(mot, document) = occurrences du mot / nombre total de mots
Exemple : calculer_tf('python python est simple') renvoie {'python': 0.5, 'est': 0.25, 'simple': 0.25} (python apparait 2 fois sur 4 mots = 0.5)
Écris une fonction calculer_tf(document) qui retourne un dictionnaire {mot: tf}.
import re
from collections import Counter
def tokeniser(texte):
mots = re.findall(r'[a-zA-ZÀ-ÿ0-9]+', texte.lower())
return [mot for mot in mots if len(mot) > 1]
def calculer_tf(document):
mots = tokeniser(document)
if not mots:
return {}
total = len(mots)
compteur = Counter(mots)
return {mot: count / total for mot, count in compteur.items()}