Skip to content

Instantly share code, notes, and snippets.

@ILPlais
Created October 1, 2024 12:14
Show Gist options
  • Select an option

  • Save ILPlais/e61a334c8457706fb5792dd8ef8899d9 to your computer and use it in GitHub Desktop.

Select an option

Save ILPlais/e61a334c8457706fb5792dd8ef8899d9 to your computer and use it in GitHub Desktop.
Corrige les erreurs typographiques courantes dans un fichier texte français
#!/usr/bin/env python3
import re
import argparse
import sys
def corriger_texte(texte):
# Espace insécable Unicode
espace_insecable = '\u00A0'
# Correction des espaces avant la ponctuation
texte = re.sub(r'\s+([.,;:!?])', r'\1', texte)
# Ajout d'espaces insécables avant les ponctuations doubles
texte = re.sub(r'\s*([;:!?])', f'{espace_insecable}\\1', texte)
# Ajout d'espaces insécables pour les guillemets français
texte = re.sub(r'«\s*', f'«{espace_insecable}', texte)
texte = re.sub(r'\s*»', f'{espace_insecable}»', texte)
# Ajout d'espaces normaux après la ponctuation si nécessaire
texte = re.sub(r'([.,;:!?])(?=[^\s])', r'\1 ', texte)
# Correction des guillemets français
texte = re.sub(r'"([^"]*)"', f'«{espace_insecable}\\1{espace_insecable}»', texte)
# Correction des apostrophes
texte = texte.replace("'", "'")
# Majuscule après un point
texte = re.sub(r'(\.\s)([a-zàâçéèêëîïôûùüÿñæœ])', lambda m: m.group(1) + m.group(2).upper(), texte)
return texte
def main():
parser = argparse.ArgumentParser(description="Corrige les erreurs typographiques courantes dans un fichier texte français.")
parser.add_argument("fichier_entree", help="Le fichier texte à corriger")
parser.add_argument("-o", "--output", help="Le fichier de sortie (par défaut: <fichier_entree>_corrige.txt)")
parser.add_argument("-v", "--verbose", action="store_true", help="Affiche des informations détaillées pendant l'exécution")
args = parser.parse_args()
fichier_entree = args.fichier_entree
fichier_sortie = args.output or fichier_entree.rsplit('.', 1)[0] + '_corrige.txt'
try:
with open(fichier_entree, 'r', encoding='utf-8') as f_entree:
texte = f_entree.read()
if args.verbose:
print(f"Lecture du fichier {fichier_entree}")
texte_corrige = corriger_texte(texte)
with open(fichier_sortie, 'w', encoding='utf-8') as f_sortie:
f_sortie.write(texte_corrige)
if args.verbose:
print(f"Écriture du fichier corrigé dans {fichier_sortie}")
print(f"Correction terminée. Résultat sauvegardé dans {fichier_sortie}")
except IOError as e:
print(f"Erreur lors de la lecture ou de l'écriture du fichier : {e}", file=sys.stderr)
sys.exit(1)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment