Python Forum
Block of code, scope of variables and surprising exception
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Block of code, scope of variables and surprising exception
#9
Hi

I think I have at last understood, and I hope this new code conforms to your advice :

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#pour classer les mots d'une phrase par ordre alphabétique
#liste=str.split(phrase)
#liste.sort(key=grec_vocab.atone)

def les_dia():
	"""Noms anglais des diacritiques."""
	return  {'DASIA', 'DIALYTIKA', 'MACRON', 'OXIA', 'PERISPOMENI', 'PROSGEGRAMMENI', 'PSILI', 'TONOS', 'VARIA', 'VRACHY', 'YPOGEGRAMMENI'}
def les_symb():
	"""Symboles qui portent le nom de lettres."""
	return {"BETA", "EPSILON", "KAPPA", "PHI", "PI", "RHO", "SIGMA", "THETA", "UPSILON"}
def les_grecques():
	"""Fichier des lettres et leurs caractéristiques"""
	return '/home/remi/Documents/programmation/python/grec_vocab/grec.xhtml'
def les_unicodes():
	"""Url des pages de définition des lettres"""
	return "https://unicode-table.com/fr/blocks/greek-coptic/", "https://unicode-table.com/fr/blocks/greek-extended/"
def la_table():
	"""Table de correspondance."""
	return '/home/remi/Documents/programmation/python/grec_vocab/tabTrans.py'
def les_determ():
	"""Éléments du nom qui déterminent la traduction."""
	return {"CAPITAL", "WITH", "SYMBOL"}
def les_minus():
	"""Début du nom des lettres minuscules."""
	return {"GREEK SMALL LETTER " }
def le_rep():
	"""Répertoire du script."""
	return '/home/remi/Documents/programmation/python/grec_vocab'

from html.parser import HTMLParser

class MyHTMLParser(HTMLParser):
################# traitement des tags de début (<tag	…)
	dic=dict()
	def handle_starttag(self, tag, attrs):
		if tag == 'div' and len(attrs) > 2 and "disabled" not in attrs[0][1] and attrs[1][0] == 'data-symbol':
			symbol=attrs[1][1]
			titre=attrs[2][1]
			unicd=attrs[3][1]
			atone=atonique(symbol)
			if atone[0]!=symbol:
				self.dic[symbol]=atone[0]
	def fin (self):
		return self.dic

def lire_tabTrans():
	import pickle
	try:
		with open(la_table(),"rb") as traduc:
			données=pickle.Unpickler(traduc)
			dictionnaire=données.load()
	except FileNotFoundError:
		dictionnaire=[]
	return dictionnaire

def enreg_tabTrans(dictionnaire):
	import pickle
	with open(la_table(),"wb") as les_données:
		données=pickle.Pickler(les_données)
		données.dump(dictionnaire)
	return 0

def atonique (polytonique: str) -> str:
	"""Caractère rendu minuscule et exempt de diacritiques.

		Recherche dans le nom standard Unicode, en anglais, de la présence de mots nécessitant le traitement"""
	import unicodedata
	nom_Unicode=unicodedata.name(polytonique)
	liste_termes=set(nom_Unicode.split(None, -1))
	liste_dia={}
	nat="minus"
	lettre=""
	if len(les_determ().intersection(liste_termes)) > 0:
		if "SYMBOL" in nom_Unicode:
			symbole=les_symb().intersection (liste_termes)
			if len(symbole) > 0:
				nom_Unicode="GREEK SMALL LETTER " + symbole.pop()
		else:
			if "WITH" in nom_Unicode:
				nom_Unicode=nom_Unicode[: nom_Unicode.find("WITH")-1]
				liste_dia=liste_termes.intersection(les_dia())
			if "CAPITAL" in nom_Unicode:
				nom_Unicode=nom_Unicode.replace("CAPITAL", "SMALL")
				nat="majus"
	try:
		LeCaract=unicodedata.lookup(nom_Unicode)
	except:
# le nom du caractère minuscule Yot ('GREEK LETTER YOT) ne contient pas le mot SMALL
		LeCaract="ϳ"
	return LeCaract, lettre, liste_dia, nat

def gen_xml (nom, symbole, code, dia, nat):
	xml="<carac "
	xml=xml+"id='" + symbole + "' "
	xml=xml +"titre='" + nom + "' "
	print("<carac id='" + symbole +"' titre='" + nom + "' unicode='" + code.split("/")[2] +"' />")

def gen_dic_trad ():
	import requests
	parser=MyHTMLParser(convert_charrefs=True)
	for bloc in les_unicodes():
		try:
			html=requests.get(bloc, timeout=2 )
		except requests.exceptions.ConnectionError:
			print("La connexion au site de l'Unicode n'a pas pu être établie")
			return False
		except requests.exceptions.Timeout:
			print("Le serveur de l'Unicode ne répond pas")
			return False
		else:
			pass
		parser.feed(html.text)
	table=parser.fin()
	parser.close()
	enreg_tabTrans(table)
	return table

def atone(mot_polytone: str)  -> str:
	dictrans=lire_tabTrans()
	if len(dictrans) == 0:
		dictrans=gen_dic_trad()
	table=str.maketrans(dictrans)
	return mot_polytone.translate(table)

def charge():
	importlib.reload("grec_vocab")

import sys

if len(sys.path[0]) == 0:
	sys.path[0]=le_rep()
	import importlib
import grec_vocab as gr

if __name__ == "__main__":
	liste=sys.argv[1:]
	liste.sort(key=atone)
	print(liste)
Arbiel
Reply


Messages In This Thread
RE: Block of code, scope of variables and surprising exception - by arbiel - Apr-06-2020, 07:57 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  How to create a variable only for use inside the scope of a while loop? Radical 10 1,825 Nov-07-2023, 09:49 AM
Last Post: buran
  Library scope mike_zah 2 868 Feb-23-2023, 12:20 AM
Last Post: mike_zah
  python multiple try except block in my code -- can we shorten code mg24 10 6,218 Nov-10-2022, 12:48 PM
Last Post: DeaD_EyE
  Scope of variable confusion Mark17 10 2,898 Feb-24-2022, 06:03 PM
Last Post: deanhystad
  "If Len(Word) == 0" Code Block in Pig Latin Program new_coder_231013 3 2,094 Jan-02-2022, 06:03 PM
Last Post: deanhystad
  Variable scope issue melvin13 2 1,567 Nov-29-2021, 08:26 PM
Last Post: melvin13
  Try,Except,Else to check that user has entered either y or n (Code block pasted) RandomNameGenerator 3 2,352 Jun-29-2021, 08:21 PM
Last Post: RandomNameGenerator
  Variable scope - "global x" didn't work... ptrivino 5 3,086 Dec-28-2020, 04:52 PM
Last Post: ptrivino
  Python Closures and Scope muzikman 2 1,833 Dec-14-2020, 11:21 PM
Last Post: muzikman
  code with exception arguments doen't work MaartenRo 1 1,970 Aug-09-2020, 06:06 AM
Last Post: Gribouillis

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020