Exercice 5
Créer un projet django nommé text_analyser et une application Django nommée Analyzer (structure de base). Un champ de saisie texte et un bouton "Analyse" valident l'opération. Au clic, analyser le texte saisi (traitement backend) et afficher:
- nombre de mots (total de mots)
- nombre de lignes (retours à la ligne)
- nombre de caractères (lettres et espaces)
- le mot le plus long (longueur maximale)
Solution
Cet exercice django explique comment créer un projet Django nommé text_analyser avec une application Analyzer qui analyse un texte saisi par l'utilisateur.
1. Configuration du projet
Structure du projet
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
text_analyser/ ├── text_analyser/ │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── Analyzer/ │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── forms.py │ ├── models.py │ ├── tests.py │ ├── urls.py │ └── views.py ├── templates/ │ └── index.html └── manage.py |
text_analyser/settings.py
Ajouter l'application à la liste des applications installées au niveau du fichier settings.py
|
1 2 3 4 5 6 7 8 9 10 |
# Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'Analyzer', # Add Analyzer app ] |
text_analyser/urls.py
|
1 2 3 4 5 6 7 8 9 |
# Main URL configuration for text_analyser project. from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('Analyzer.urls')), # Include Analyzer app URLs ] |
2. Création de l'application Analyzer
Analyzer/forms.py
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
""" Forms for the Analyzer application. """ from django import forms class TextAnalysisForm(forms.Form): """ Form for text input to be analyzed. """ input_text = forms.CharField( label='Enter your text', widget=forms.Textarea(attrs={ 'rows': 10, 'cols': 80, 'placeholder': 'Type or paste your text here...' }), required=True ) |
Analyzer/views.py
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
""" Views for the Analyzer application. """ from django.shortcuts import render from .forms import TextAnalysisForm def index(request): """ Main view that handles text analysis. Displays the input form and analysis results. """ context = {} if request.method == 'POST': form = TextAnalysisForm(request.POST) if form.is_valid(): # Get the text from the form input_text = form.cleaned_data['input_text'] # Perform text analysis analysis_results = text_analyzer(input_text) # Add results to context context['results'] = analysis_results context['input_text'] = input_text else: form = TextAnalysisForm() context['form'] = form return render(request, 'index.html', context) def text_analyzer(text): """ Analyze the input text and return statistics. Args: text (str): The text to analyze Returns: dict: Dictionary containing analysis results """ if not text: return { 'word_count': 0, 'line_count': 0, 'character_count': 0, 'longest_word': '' } # Split text into lines lines = text.splitlines() line_count = len(lines) # Split text into words (considering whitespace and newlines) words = text.split() word_count = len(words) # Count characters (excluding newlines) character_count = len(text) # Find the longest word longest_word = '' if words: longest_word = max(words, key=len) return { 'word_count': word_count, 'line_count': line_count, 'character_count': character_count, 'longest_word': longest_word } |
Analyzer/urls.py
|
1 2 3 4 5 6 7 8 9 |
""" URL configuration for Analyzer application. """ from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] |
Analyzer/apps.py
|
1 2 3 4 5 6 7 8 |
""" Application configuration for Analyzer. """ from django.apps import AppConfig class AnalyzerConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'Analyzer' |
3. Template
templates/index.html
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Text Analyzer</title> </head> <body> <h1>Text Analyzer</h1> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Analyze</button> </form> {% if results %} <h2>Analysis Results:</h2> <div> <p><strong>Number of words:</strong> {{ results.word_count }}</p> <p><strong>Number of lines:</strong> {{ results.line_count }}</p> <p><strong>Number of characters:</strong> {{ results.character_count }}</p> <p><strong>Longest word:</strong> "{{ results.longest_word }}"</p> </div> <h3>Analyzed Text:</h3> <div style="border: 1px solid #ccc; padding: 10px; margin-top: 10px;"> <pre>{{ input_text }}</pre> </div> {% endif %} </body> </html> |
4. Instructions d'installation et d'exécution
Étape 1: Créer un environnement virtuel et installer Django
|
1 2 3 |
python -m venv venv source venv/bin/activate # Sur Windows: venv\Scripts\activate pip install django |
Étape 2: Créer le projet et l'application
|
1 2 3 |
django-admin startproject text_analyser cd text_analyser python manage.py startapp Analyzer |
Étape 3: Créer les dossiers et fichiers
Créez le dossier templates à la racine du projet et placez tous les fichiers comme indiqué dans la structure ci-dessus.
Étape 4: Lancer le serveur
|
1 |
python manage.py runserver |
Étape 5: Accéder à l'application
Ouvrez votre navigateur et allez sur http://127.0.0.1:8000/
Fonctionnalités de l'application
L'application analyse le texte saisi et affiche les informations suivantes :
- Nombre de mots (word count)
- Nombre de lignes (line count)
- Nombre de caractères (character count)
- Le mot le plus long (longest word)
Auteur : Younes Derfoufi
Lieu de travail : CRMEF OUJDA
Site Web : www.tresfacile.net
Chaine YouTube : https://www.youtube.com/user/InformatiquesFacile
Me contacter : https://www.tresfacile.net/me-contacter/



