-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtext_analyzer.py
More file actions
2396 lines (2063 loc) · 89.2 KB
/
Copy pathtext_analyzer.py
File metadata and controls
2396 lines (2063 loc) · 89.2 KB
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
=============================================================================
TEXT ANALYSIS APPLICATION - Standalone Complete Version
=============================================================================
Project: Developing Text Analysis Application in Python
This single file contains:
- Version 1: Functional/Modular implementation
- Version 2: Object-Oriented implementation (TextAnalyzer class)
- Modern GUI with drag-and-drop support
- All text processing features
- Word frequency analysis
- Matplotlib visualization
Features:
✓ Type/paste text directly
✓ Load text from file (Browse button)
✓ Drag & drop .txt files
✓ Count characters (with/without spaces)
✓ Count words, sentences, paragraphs
✓ Unique word frequency analysis
✓ Top 10 most common words
✓ Bar chart visualization
✓ Two analysis methods: Functional and OOP
Author: AarontheGalaxy
GitHub: https://github.com/AarontheGalaxy
Date: December 1, 2025
🐢 Slow and steady wins the race!
=============================================================================
"""
import re
import tkinter as tk
from tkinter import ttk, scrolledtext, messagebox, filedialog
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
from collections import Counter
import os
import sys
# Try to import document readers
try:
import docx
HAS_DOCX = True
except ImportError:
HAS_DOCX = False
try:
import PyPDF2
HAS_PDF = True
except ImportError:
HAS_PDF = False
try:
from striprtf.striprtf import rtf_to_text
HAS_RTF = True
except ImportError:
HAS_RTF = False
# Try to import tkinterdnd2 for drag-and-drop, fallback if not available
try:
from tkinterdnd2 import DND_FILES, TkinterDnD
HAS_DND = True
except ImportError:
HAS_DND = False
print("⚠️ tkinterdnd2 not available. Drag-and-drop feature will be disabled.")
print(" Install with: pip install tkinterdnd2")
# =============================================================================
# MULTI-LANGUAGE SUPPORT SYSTEM
# =============================================================================
# 🐢 < "I speak turtle in every language!"
# Stop words for different languages
STOP_WORDS = {
'en': ['the', 'and', 'is', 'are', 'was', 'were', 'of', 'to', 'in', 'for', 'a', 'an',
'on', 'at', 'by', 'with', 'from', 'as', 'be', 'been', 'being', 'have', 'has',
'had', 'do', 'does', 'did', 'will', 'would', 'could', 'should', 'may', 'might',
'this', 'that', 'these', 'those', 'i', 'you', 'he', 'she', 'it', 'we', 'they'],
'tr': ['bir', 've', 'bu', 'şu', 'için', 'ile', 'de', 'da', 'den', 'dan', 'ise', 'mi',
'mı', 'mu', 'mü', 'değil', 'daha', 'çok', 'gibi', 'var', 'yok', 'ben', 'sen',
'o', 'biz', 'siz', 'onlar', 'şey', 'ne', 'nasıl', 'neden', 'niçin', 'nerede'],
'de': ['der', 'die', 'das', 'und', 'ist', 'in', 'zu', 'den', 'dem', 'des', 'ein',
'eine', 'von', 'mit', 'auf', 'für', 'an', 'als', 'auch', 'aus', 'bei', 'nach',
'um', 'über', 'ich', 'du', 'er', 'sie', 'es', 'wir', 'ihr', 'nicht', 'sich'],
'ar': ['في', 'من', 'إلى', 'على', 'هذا', 'ذلك', 'التي', 'الذي', 'هو', 'هي', 'أن',
'ما', 'لا', 'نحن', 'أنا', 'أنت', 'هم', 'كان', 'كانت', 'يكون', 'عن', 'مع'],
'es': ['el', 'la', 'de', 'que', 'y', 'a', 'en', 'un', 'una', 'los', 'las', 'del',
'por', 'para', 'con', 'no', 'se', 'lo', 'como', 'más', 'pero', 'sus', 'es',
'yo', 'tú', 'él', 'ella', 'nosotros', 'ellos', 'estar', 'ser', 'tener'],
'fr': ['le', 'la', 'de', 'et', 'un', 'une', 'est', 'pour', 'dans', 'que', 'les',
'des', 'du', 'à', 'il', 'elle', 'on', 'nous', 'vous', 'ils', 'elles', 'ce',
'ne', 'pas', 'plus', 'avec', 'par', 'sur', 'être', 'avoir', 'son', 'sa'],
'zh': ['的', '是', '在', '了', '和', '有', '我', '你', '他', '她', '它', '们', '这',
'那', '不', '也', '就', '都', '要', '会', '能', '可以', '没有', '什么', '为']
}
# Language-specific punctuation for sentence detection
SENTENCE_ENDINGS = {
'en': ['.', '!', '?'],
'tr': ['.', '!', '?'],
'de': ['.', '!', '?'],
'ar': ['。', '!', '؟', '.', '!', '?'],
'es': ['.', '!', '?', '¡', '¿'],
'fr': ['.', '!', '?'],
'zh': ['。', '!', '?', '.', '!', '?']
}
# UI Translations
TRANSLATIONS = {
'en': {
'app_title': '📊 Text Analysis Application',
'subtitle': 'Complete Version - Functional & OOP Methods',
'settings': '⚙️ Settings',
'download_modules': '📦 Download Modules',
'text_input': '📝 Text Input Area',
'instructions': '💡 Enter text OR load file (TXT, RTF, DOCX, PDF supported)',
'instructions_dnd': ' OR drag & drop files here',
'browse_file': '📁 Browse File',
'analysis_method': 'Analysis Method:',
'functional': '⚙️ Functional',
'oop': '🎯 OOP (Class)',
'analyze_text': '🔍 Analyze Text',
'clear_all': '🗑️ Clear All',
'analysis_results': '📊 Analysis Results',
'analyze_lang': 'Analyze Language:',
'auto_detect': '🌍 Auto-Detect',
'overview': '📊 Overview',
'word_analysis': '📝 Word Analysis',
'detailed_report': '📋 Detailed Report',
'language_stats': '🌐 Language Stats',
'advanced': '🔬 Advanced',
'info': 'ℹ️ Info'
},
'tr': {
'app_title': '📊 Metin Analiz Uygulaması',
'subtitle': 'Tam Sürüm - Fonksiyonel & OOP Yöntemler',
'settings': '⚙️ Ayarlar',
'download_modules': '📦 Modül İndir',
'text_input': '📝 Metin Giriş Alanı',
'instructions': '💡 Metin girin VEYA dosya yükleyin (TXT, RTF, DOCX, PDF desteklenir)',
'instructions_dnd': ' VEYA dosyaları sürükle bırak',
'browse_file': '📁 Dosya Seç',
'analysis_method': 'Analiz Yöntemi:',
'functional': '⚙️ Fonksiyonel',
'oop': '🎯 OOP (Sınıf)',
'analyze_text': '🔍 Metni Analiz Et',
'clear_all': '🗑️ Tümünü Temizle',
'analysis_results': '📊 Analiz Sonuçları',
'analyze_lang': 'Analiz Dili:',
'auto_detect': '🌍 Otomatik Algıla',
'overview': '📊 Genel Bakış',
'word_analysis': '📝 Kelime Analizi',
'detailed_report': '📋 Detaylı Rapor',
'language_stats': '🌐 Dil İstatistikleri',
'advanced': '🔬 Gelişmiş',
'info': 'ℹ️ Bilgi'
},
'de': {
'app_title': '📊 Textanalyse-Anwendung',
'subtitle': 'Vollversion - Funktionale & OOP-Methoden',
'settings': '⚙️ Einstellungen',
'download_modules': '📦 Module Herunterladen',
'text_input': '📝 Texteingabebereich',
'instructions': '💡 Text eingeben ODER Datei laden (TXT, RTF, DOCX, PDF unterstützt)',
'instructions_dnd': ' ODER Dateien hier ablegen',
'browse_file': '📁 Datei Durchsuchen',
'analysis_method': 'Analysemethode:',
'functional': '⚙️ Funktional',
'oop': '🎯 OOP (Klasse)',
'analyze_text': '🔍 Text Analysieren',
'clear_all': '🗑️ Alles Löschen',
'analysis_results': '📊 Analyseergebnisse',
'analyze_lang': 'Analysesprache:',
'auto_detect': '🌍 Auto-Erkennung',
'overview': '📊 Übersicht',
'word_analysis': '📝 Wortanalyse',
'detailed_report': '📋 Detaillierter Bericht',
'language_stats': '🌐 Sprachstatistik',
'advanced': '🔬 Erweitert',
'info': 'ℹ️ Info'
},
'ar': {
'app_title': '📊 تطبيق تحليل النصوص',
'subtitle': 'النسخة الكاملة - الطرق الوظيفية والكائنية',
'settings': '⚙️ الإعدادات',
'download_modules': '📦 تحميل الوحدات',
'text_input': '📝 منطقة إدخال النص',
'instructions': '💡 أدخل النص أو حمل ملف (TXT, RTF, DOCX, PDF مدعوم)',
'instructions_dnd': ' أو اسحب وأفلت الملفات هنا',
'browse_file': '📁 تصفح الملف',
'analysis_method': 'طريقة التحليل:',
'functional': '⚙️ وظيفي',
'oop': '🎯 OOP (فئة)',
'analyze_text': '🔍 تحليل النص',
'clear_all': '🗑️ مسح الكل',
'analysis_results': '📊 نتائج التحليل',
'analyze_lang': 'لغة التحليل:',
'auto_detect': '🌍 الكشف التلقائي',
'overview': '📊 نظرة عامة',
'word_analysis': '📝 تحليل الكلمات',
'detailed_report': '📋 تقرير مفصل',
'language_stats': '🌐 إحصائيات اللغة',
'advanced': '🔬 متقدم',
'info': 'ℹ️ معلومات'
},
'es': {
'app_title': '📊 Aplicación de Análisis de Texto',
'subtitle': 'Versión Completa - Métodos Funcionales y OOP',
'settings': '⚙️ Configuración',
'download_modules': '📦 Descargar Módulos',
'text_input': '📝 Área de Entrada de Texto',
'instructions': '💡 Ingrese texto O cargue archivo (TXT, RTF, DOCX, PDF compatible)',
'instructions_dnd': ' O arrastre y suelte archivos aquí',
'browse_file': '📁 Examinar Archivo',
'analysis_method': 'Método de Análisis:',
'functional': '⚙️ Funcional',
'oop': '🎯 OOP (Clase)',
'analyze_text': '🔍 Analizar Texto',
'clear_all': '🗑️ Borrar Todo',
'analysis_results': '📊 Resultados del Análisis',
'analyze_lang': 'Idioma de Análisis:',
'auto_detect': '🌍 Detección Automática',
'overview': '📊 Resumen',
'word_analysis': '📝 Análisis de Palabras',
'detailed_report': '📋 Informe Detallado',
'language_stats': '🌐 Estadísticas de Idioma',
'advanced': '🔬 Avanzado',
'info': 'ℹ️ Información'
},
'fr': {
'app_title': "📊 Application d'Analyse de Texte",
'subtitle': 'Version Complète - Méthodes Fonctionnelles et POO',
'settings': '⚙️ Paramètres',
'download_modules': '📦 Télécharger Modules',
'text_input': '📝 Zone de Saisie de Texte',
'instructions': '💡 Entrez du texte OU chargez un fichier (TXT, RTF, DOCX, PDF pris en charge)',
'instructions_dnd': ' OU glissez-déposez les fichiers ici',
'browse_file': '📁 Parcourir Fichier',
'analysis_method': "Méthode d'Analyse:",
'functional': '⚙️ Fonctionnelle',
'oop': '🎯 POO (Classe)',
'analyze_text': '🔍 Analyser le Texte',
'clear_all': '🗑️ Tout Effacer',
'analysis_results': "📊 Résultats de l'Analyse",
'analyze_lang': "Langue d'Analyse:",
'auto_detect': '🌍 Détection Automatique',
'overview': '📊 Vue d\'ensemble',
'word_analysis': '📝 Analyse des Mots',
'detailed_report': '📋 Rapport Détaillé',
'language_stats': '🌐 Statistiques Linguistiques',
'advanced': '🔬 Avancé',
'info': 'ℹ️ Info'
},
'zh': {
'app_title': '📊 文本分析应用程序',
'subtitle': '完整版 - 函数式和面向对象方法',
'settings': '⚙️ 设置',
'download_modules': '📦 下载模块',
'text_input': '📝 文本输入区域',
'instructions': '💡 输入文本或加载文件(支持TXT、RTF、DOCX、PDF)',
'instructions_dnd': ' 或将文件拖放到此处',
'browse_file': '📁 浏览文件',
'analysis_method': '分析方法:',
'functional': '⚙️ 函数式',
'oop': '🎯 面向对象(类)',
'analyze_text': '🔍 分析文本',
'clear_all': '🗑️ 清除全部',
'analysis_results': '📊 分析结果',
'analyze_lang': '分析语言:',
'auto_detect': '🌍 自动检测',
'overview': '📊 概述',
'word_analysis': '📝 词汇分析',
'detailed_report': '📋 详细报告',
'language_stats': '🌐 语言统计',
'advanced': '🔬 高级',
'info': 'ℹ️ 信息'
}
}
# Language names for display
LANGUAGE_NAMES = {
'en': '🇬🇧 English',
'tr': '🇹🇷 Türkçe',
'de': '🇩🇪 Deutsch',
'ar': '🇸🇦 العربية',
'es': '🇪🇸 Español',
'fr': '🇫🇷 Français',
'zh': '🇨🇳 中文'
}
def detect_language(text):
"""
Detect the language of the given text.
Returns tuple: (language_code, confidence, distribution)
"""
text_lower = text.lower()
words = re.findall(r'\w+', text_lower)
if not words:
return 'en', 0.0, {}
# Count matches for each language
language_scores = {}
for lang, stop_words in STOP_WORDS.items():
matches = sum(1 for word in words if word in stop_words)
language_scores[lang] = matches
# Calculate total matches
total_matches = sum(language_scores.values())
if total_matches == 0:
# Check for language-specific characters
if any('\u4e00' <= c <= '\u9fff' for c in text):
return 'zh', 0.95, {'zh': 0.95}
elif any('\u0600' <= c <= '\u06ff' for c in text):
return 'ar', 0.95, {'ar': 0.95}
else:
return 'en', 0.50, {'en': 0.50}
# Calculate distribution
distribution = {lang: score/total_matches for lang,
score in language_scores.items() if score > 0}
# Find dominant language
dominant_lang = max(language_scores, key=language_scores.get)
confidence = language_scores[dominant_lang] / total_matches
return dominant_lang, confidence, distribution
# =============================================================================
# VERSION 1: FUNCTIONAL/MODULAR IMPLEMENTATION
# =============================================================================
# 🐢 < "I count characters one by one..."
def count_characters_with_spaces(text_lines):
"""
Count total characters including spaces.
Args:
text_lines (list): List of text lines
Returns:
int: Total character count including spaces
"""
full_text = '\n'.join(text_lines)
return len(full_text)
def count_characters_without_spaces(text_lines):
"""
Count total characters excluding whitespace.
Args:
text_lines (list): List of text lines
Returns:
int: Total character count excluding spaces
"""
full_text = '\n'.join(text_lines)
return len(re.sub(r'\s', '', full_text))
def count_words(text_lines):
"""
Count total words in the text (ignoring punctuation).
Words are separated by spaces and punctuation is removed.
Args:
text_lines (list): List of text lines
Returns:
int: Total word count
"""
full_text = ' '.join(text_lines)
# Extract words using regex (alphanumeric sequences)
words = re.findall(r'\b\w+\b', full_text)
return len(words)
def count_sentences(text_lines):
"""
Count total sentences based on sentence-ending punctuation (. ! ?).
Args:
text_lines (list): List of text lines
Returns:
int: Total sentence count
"""
full_text = ' '.join(text_lines)
# Split by sentence-ending punctuation
sentences = re.split(r'[.!?]+', full_text)
# Filter out empty strings
sentences = [s for s in sentences if s.strip()]
return len(sentences)
def count_paragraphs(text_lines):
"""
Count paragraphs (blocks of text separated by empty lines).
Args:
text_lines (list): List of text lines
Returns:
int: Total paragraph count
"""
paragraph_count = 0
in_paragraph = False
for line in text_lines:
if line.strip(): # Non-empty line
if not in_paragraph:
paragraph_count += 1
in_paragraph = True
else: # Empty line
in_paragraph = False
return paragraph_count
def analyze_word_frequency(text_lines):
"""
Analyze word frequency (lowercase, no punctuation).
Args:
text_lines (list): List of text lines
Returns:
dict: Dictionary with words as keys and their frequencies as values
"""
full_text = ' '.join(text_lines)
# Convert to lowercase and extract words
words = re.findall(r'\b\w+\b', full_text.lower())
# Count frequencies using Counter
word_freq = Counter(words)
return dict(word_freq)
def get_text_statistics_functional(text_lines):
"""
Generate all text statistics using functional approach.
This is the main function for Version 1 (Functional Implementation).
Args:
text_lines (list): List of text lines
Returns:
tuple: (stats dict, word_freq dict)
"""
stats = {
'total_chars_with_spaces': count_characters_with_spaces(text_lines),
'total_chars_without_spaces': count_characters_without_spaces(text_lines),
'total_words': count_words(text_lines),
'total_sentences': count_sentences(text_lines),
'total_paragraphs': count_paragraphs(text_lines)
}
word_freq = analyze_word_frequency(text_lines)
return stats, word_freq
# =============================================================================
# FILE READING FUNCTIONS (Multiple Format Support)
# =============================================================================
# 🐢 < "I can read anything... slowly but surely!"
def read_txt_file(file_path):
"""Read plain text file."""
with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
return f.read()
def read_rtf_file(file_path):
"""Read RTF file."""
if not HAS_RTF:
raise ImportError(
"striprtf library required. Install: pip install striprtf")
with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
rtf_content = f.read()
return rtf_to_text(rtf_content)
def read_docx_file(file_path):
"""Read DOCX file."""
if not HAS_DOCX:
raise ImportError(
"python-docx library required. Install: pip install python-docx")
doc = docx.Document(file_path)
full_text = []
for para in doc.paragraphs:
full_text.append(para.text)
return '\n'.join(full_text)
def read_pdf_file(file_path):
"""Read PDF file."""
if not HAS_PDF:
raise ImportError(
"PyPDF2 library required. Install: pip install PyPDF2")
text = []
with open(file_path, 'rb') as f:
pdf_reader = PyPDF2.PdfReader(f)
for page in pdf_reader.pages:
text.append(page.extract_text())
return '\n'.join(text)
def read_file_auto(file_path):
"""
Automatically detect file type and read content.
Args:
file_path (str): Path to file
Returns:
str: File content as text
"""
ext = os.path.splitext(file_path)[1].lower()
readers = {
'.txt': read_txt_file,
'.rtf': read_rtf_file,
'.docx': read_docx_file,
'.pdf': read_pdf_file,
'.doc': read_docx_file # Try with docx reader
}
if ext in readers:
return readers[ext](file_path)
else:
# Try as plain text
return read_txt_file(file_path)
# =============================================================================
# VERSION 2: OBJECT-ORIENTED IMPLEMENTATION
# =============================================================================
# 🐢 < "OOP makes me feel classy!"
class TextAnalyzer:
"""
A class to analyze text and provide comprehensive statistics.
This is Version 2 (Object-Oriented Implementation).
Attributes:
text_lines (list): Text stored as a list of strings (lines)
stats (dict): Dictionary containing text statistics
word_freq (dict): Dictionary containing word frequency data
"""
def __init__(self, text_lines):
"""
Initialize the TextAnalyzer with text lines.
Args:
text_lines (list): List of text lines to analyze
"""
self.text_lines = text_lines
self.stats = {}
self.word_freq = {}
def count_characters_with_spaces(self):
"""
Count total characters including spaces.
Returns:
int: Total character count including spaces
"""
full_text = '\n'.join(self.text_lines)
return len(full_text)
def count_characters_without_spaces(self):
"""
Count total characters excluding whitespace.
Returns:
int: Total character count excluding spaces
"""
full_text = '\n'.join(self.text_lines)
return len(re.sub(r'\s', '', full_text))
def count_words(self):
"""
Count total words in the text (ignoring punctuation).
Returns:
int: Total word count
"""
full_text = ' '.join(self.text_lines)
words = re.findall(r'\b\w+\b', full_text)
return len(words)
def count_sentences(self):
"""
Count total sentences based on sentence-ending punctuation.
Returns:
int: Total sentence count
"""
full_text = ' '.join(self.text_lines)
sentences = re.split(r'[.!?]+', full_text)
sentences = [s for s in sentences if s.strip()]
return len(sentences)
def count_paragraphs(self):
"""
Count paragraphs (blocks of text separated by empty lines).
Returns:
int: Total paragraph count
"""
paragraph_count = 0
in_paragraph = False
for line in self.text_lines:
if line.strip():
if not in_paragraph:
paragraph_count += 1
in_paragraph = True
else:
in_paragraph = False
return paragraph_count
def analyze_word_frequency(self):
"""
Analyze word frequency (lowercase, no punctuation).
Returns:
dict: Dictionary with words as keys and their frequencies as values
"""
full_text = ' '.join(self.text_lines)
words = re.findall(r'\b\w+\b', full_text.lower())
word_freq = Counter(words)
return dict(word_freq)
def calculate_statistics(self):
"""
Calculate all text statistics and store in the stats dictionary.
This is the main method that performs all analysis.
Returns:
tuple: (stats dict, word_freq dict)
"""
self.stats = {
'total_chars_with_spaces': self.count_characters_with_spaces(),
'total_chars_without_spaces': self.count_characters_without_spaces(),
'total_words': self.count_words(),
'total_sentences': self.count_sentences(),
'total_paragraphs': self.count_paragraphs()
}
self.word_freq = self.analyze_word_frequency()
return self.stats, self.word_freq
# =============================================================================
# GUI APPLICATION
# =============================================================================
# 🐢 < "GUIs are my shell!"
class TextAnalysisApp:
"""
Main GUI application for text analysis with drag-and-drop support.
Combines both Functional and OOP analysis methods in one interface.
"""
def __init__(self, root):
"""
Initialize the GUI application.
Args:
root: Tkinter root window
"""
self.root = root
# Language settings
self.ui_language = 'en' # Interface language
self.analysis_language = 'auto' # Text analysis language
self.detected_language = None # Auto-detected language
self.language_confidence = 0.0
self.language_distribution = {}
self.root.title("📊 Text Analysis Application - Complete Version")
self.root.geometry("1100x850")
# Theme settings
self.current_theme = 'light' # 'light' or 'dark'
self.mini_project_mode = False # Simple mode for teacher requirements
self.themes = {
'light': {
'bg': '#ffffff',
'fg': '#000000',
'text_bg': '#ffffff',
'text_fg': '#000000',
'button_bg': '#e0e0e0',
'frame_bg': '#f5f5f5'
},
'dark': {
'bg': '#2b2b2b',
'fg': '#ffffff',
'text_bg': '#1e1e1e',
'text_fg': '#d4d4d4',
'button_bg': '#3c3c3c',
'frame_bg': '#252525'
}
}
# Configure style
style = ttk.Style()
try:
style.theme_use('clam')
except tk.TclError:
pass # Use default theme if clam is not available
self.create_widgets()
def tr(self, key):
"""Get translation for current UI language."""
return TRANSLATIONS.get(self.ui_language, TRANSLATIONS['en']).get(key, key)
def change_ui_language(self, _event=None):
"""Change the UI language."""
selected = self.ui_lang_var.get()
# Find language code from display name
for code, name in LANGUAGE_NAMES.items():
if name == selected:
self.ui_language = code
break
self.update_ui_language()
def change_analysis_language(self, _event=None):
"""Change the analysis language."""
selected = self.analysis_lang_var.get()
# Check if Auto-Detect is selected
if selected == self.tr('auto_detect'):
self.analysis_language = 'auto'
return
# Find language code from display name
for code, name in LANGUAGE_NAMES.items():
if name == selected:
self.analysis_language = code
break
def update_ui_language(self):
"""Update all UI elements with new language."""
self.title_label.config(text=self.tr('app_title'))
self.subtitle_label.config(text=self.tr('subtitle'))
self.download_btn.config(text=self.tr('download_modules'))
self.settings_btn.config(text=self.tr('settings'))
# Update other widgets if they exist
if hasattr(self, 'input_label_frame'):
self.input_label_frame.config(text=self.tr('text_input'))
if hasattr(self, 'browse_btn'):
self.browse_btn.config(text=self.tr('browse_file'))
if hasattr(self, 'analyze_btn'):
self.analyze_btn.config(text=self.tr('analyze_text'))
if hasattr(self, 'clear_btn'):
self.clear_btn.config(text=self.tr('clear_all'))
if hasattr(self, 'results_label_frame'):
self.results_label_frame.config(text=self.tr('analysis_results'))
def create_widgets(self):
"""Create and layout all GUI widgets."""
# Main container
main_frame = ttk.Frame(self.root, padding="15")
main_frame.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
# Configure grid weights for responsiveness
self.root.columnconfigure(0, weight=1)
self.root.rowconfigure(0, weight=1)
main_frame.columnconfigure(0, weight=1)
main_frame.rowconfigure(1, weight=1)
main_frame.rowconfigure(3, weight=1)
# =====================================================================
# HEADER SECTION
# =====================================================================
header_frame = ttk.Frame(main_frame)
header_frame.grid(row=0, column=0, sticky=(tk.W, tk.E), pady=(0, 15))
self.title_label = ttk.Label(
header_frame,
text="📊 Text Analysis - Mini Project Mode" if self.mini_project_mode else self.tr(
'app_title'),
font=('Helvetica', 22, 'bold'),
foreground='#2c3e50'
)
self.title_label.pack(side=tk.LEFT)
self.subtitle_label = ttk.Label(
header_frame,
text=self.tr(
'subtitle') if not self.mini_project_mode else "Basic Implementation - Functional & OOP Methods",
font=('Helvetica', 10),
foreground='#7f8c8d'
)
self.subtitle_label.pack(side=tk.LEFT, padx=(10, 0))
# UI Language selector frame - Always create, conditionally show
self.ui_lang_frame = ttk.Frame(header_frame)
self.ui_lang_label = ttk.Label(self.ui_lang_frame, text="Language:")
self.ui_lang_label.pack(side=tk.LEFT, padx=(0, 5))
self.ui_lang_var = tk.StringVar(
value=LANGUAGE_NAMES.get(self.ui_language, '🇬🇧 English'))
self.ui_lang_combo = ttk.Combobox(
self.ui_lang_frame,
textvariable=self.ui_lang_var,
values=list(LANGUAGE_NAMES.values()),
state='readonly',
width=15
)
self.ui_lang_combo.pack(side=tk.LEFT)
self.ui_lang_combo.bind('<<ComboboxSelected>>',
self.change_ui_language)
# Pack frame only if not in mini mode
if not self.mini_project_mode:
self.ui_lang_frame.pack(side=tk.RIGHT, padx=(5, 0))
# Download Modules button - Always create, conditionally show
self.download_btn = ttk.Button(
header_frame,
text=self.tr('download_modules'),
command=self.open_download_manager,
width=18
)
if not self.mini_project_mode:
self.download_btn.pack(side=tk.RIGHT, padx=(5, 0))
# Settings button (always visible)
self.settings_btn = ttk.Button(
header_frame,
text=self.tr('settings'),
command=self.open_settings,
width=12
)
self.settings_btn.pack(side=tk.RIGHT, padx=(10, 0))
# =====================================================================
# INPUT SECTION
# =====================================================================
self.input_label_frame = ttk.LabelFrame(
main_frame,
text=self.tr('text_input'),
padding="15"
)
self.input_label_frame.grid(row=1, column=0, sticky=(
tk.W, tk.E, tk.N, tk.S), pady=(0, 15))
self.input_label_frame.columnconfigure(0, weight=1)
self.input_label_frame.rowconfigure(1, weight=1)
# Instructions with language selector (simplified in mini mode)
inst_frame = ttk.Frame(self.input_label_frame)
inst_frame.grid(row=0, column=0, sticky=(tk.W, tk.E), pady=(0, 8))
self.inst_frame = inst_frame # Save reference for toggling
instructions_text = "💡 Enter text OR load file (TXT, RTF, DOCX, PDF supported)" if self.mini_project_mode else self.tr(
'instructions')
if HAS_DND:
instructions_text += " OR drag & drop files here" if self.mini_project_mode else self.tr(
'instructions_dnd')
self.inst_label = ttk.Label(
inst_frame,
text=instructions_text,
foreground='#3498db',
font=('Helvetica', 10)
)
self.inst_label.pack(side=tk.LEFT)
# Analysis Language selector - Always create, conditionally show
self.analysis_lang_label = ttk.Label(
inst_frame,
text=" | " + self.tr('analyze_lang'),
font=('Helvetica', 10, 'bold'),
foreground='#2c3e50'
)
self.analysis_lang_var = tk.StringVar(value=self.tr('auto_detect'))
analysis_langs = [self.tr('auto_detect')] + \
list(LANGUAGE_NAMES.values())
self.analysis_lang_combo = ttk.Combobox(
inst_frame,
textvariable=self.analysis_lang_var,
values=analysis_langs,
state='readonly',
width=18
)
self.analysis_lang_combo.bind(
'<<ComboboxSelected>>', self.change_analysis_language)
# Pack only if not in mini mode
if not self.mini_project_mode:
self.analysis_lang_label.pack(side=tk.LEFT, padx=(15, 5))
self.analysis_lang_combo.pack(side=tk.LEFT)
# Text area with scrollbar
theme = self.themes[self.current_theme]
self.text_area = scrolledtext.ScrolledText(
self.input_label_frame,
wrap=tk.WORD,
width=90,
height=12,
font=('Courier', 11),
borderwidth=2,
relief=tk.GROOVE,
background=theme['text_bg'],
foreground=theme['text_fg'],
insertbackground=theme['text_fg']
)
self.text_area.grid(row=1, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
# Enable drag and drop if available
if HAS_DND:
try:
self.text_area.drop_target_register(DND_FILES) # type: ignore
self.text_area.dnd_bind(
'<<Drop>>', self.drop_file) # type: ignore
except AttributeError:
pass # Drag and drop not available
# =====================================================================
# CONTROL BUTTONS SECTION
# =====================================================================
button_frame = ttk.Frame(main_frame)
button_frame.grid(row=2, column=0, pady=12)
# Browse button
self.browse_btn = ttk.Button(
button_frame,
text=self.tr('browse_file'),
command=self.browse_file,
width=15
)
self.browse_btn.grid(row=0, column=0, padx=8)
# Separator
ttk.Separator(button_frame, orient=tk.VERTICAL).grid(
row=0, column=1, sticky='ns', padx=15
)
# Analysis method selection
method_label = ttk.Label(
button_frame,
text=self.tr('analysis_method'),
font=('Helvetica', 10, 'bold')
)
method_label.grid(row=0, column=2, padx=(5, 10))
self.analysis_method = tk.StringVar(value="functional")
functional_radio = ttk.Radiobutton(
button_frame,
text=self.tr('functional'),
variable=self.analysis_method,
value="functional"
)
functional_radio.grid(row=0, column=3, padx=5)
oop_radio = ttk.Radiobutton(
button_frame,
text=self.tr('oop'),
variable=self.analysis_method,
value="oop"
)
oop_radio.grid(row=0, column=4, padx=5)
# Separator
ttk.Separator(button_frame, orient=tk.VERTICAL).grid(
row=0, column=5, sticky='ns', padx=15
)
# Analyze button (highlighted)
self.analyze_btn = ttk.Button(
button_frame,
text=self.tr('analyze_text'),
command=self.analyze_text,
width=18
)
self.analyze_btn.grid(row=0, column=6, padx=8)
# Clear button
self.clear_btn = ttk.Button(
button_frame,
text=self.tr('clear_all'),
command=self.clear_all,
width=12
)