Bonjour je suis en première spécial NSI et mon professeur nous a donné un projet et j'ai une erreur dans mon programme que je ne comprend pas (Je tiens à préciser que j'ai bien le dossier ressource sur mon ordinateur. Dans ce dossier il y a trois fichier french.lg, english.lg et russian.lg et dans ces fichier six mots de chaque langue sont inscrit dedans)
Quand je lance mon programme cette erreur apparait:
Traceback (most recent call last):
File "/Users/ethan/Desktop/eleveProjet/hangman.py", line 600, in <module>
dictionary = read_dictionary_file(name_of_dictionaries[language])
File "/Users/ethan/Desktop/eleveProjet/hangman.py", line 233, in read_dictionary_file
raise FileNotFoundError("Le fichier "+name_file+" n\'est pas présent dans le répertoire resources/")
FileNotFoundError: Le fichier english.lg n'est pas présent dans le répertoire resources/
Que puis je faire ?
En tout cas merci d'avance pour vos réponses
Voici mon programme
# -*- coding: utf-8 -*-
base (12 ptns)
IMP1 vérifier que l'utilisateur n'a pas déjà rentré une lettre (2 pnts)
IMP2 gérer en entrée des minuscules ou des majuscules (==> conversion) (1pnts)
IMP3 gestion de langues multiples (on leur fournira 3 fichiers: français, anglais et russe) (3pnts)
Lettres russe : https://www.lexilogos.com/russe_alphabet_cyrillique.htm
on considère les lettres Е Ё comme une seule et même lettre Е
'А Б В Г Д Е Ё Ж З И Й К Л М Н О П Р С Т У Ф Х Ц Ч Ш Щ Ъ Ы Ь Э Ю Я'
'а б в г д е ё ж з и й к л м н о п р с т у ф х ц ч ш щ ъ ы ь э ю я'
IMP4 utilisation des fréquences de lettres en français puis dans les autres langues pour recommander à l'utilisateur la prochaine lettre
(4 pnts + 1 pnts si multi langues)
https://fr.wikipedia.org/wiki/Fr%C3%A9quence_d%27apparition_des_lettres
https://www.apprendre-en-ligne.net/crypto/stat/russe.html
IMP5 dessiner le pendu avec un module graphique (2pnts)
"""
import os
import sys
import random
# ------------------------------------------------------------------------------------------------------
# CONSTANTS & GLOBALS
NOM_ELEVE1 = ""
CLASSE_ELEVE1 = 100
NOM_ELEVE2 = ""
CLASSE_ELEVE2 = 100
# améliorations implémentées
IMP1 = True
IMP2 = True
IMP3 = True
IMP4 = True
IMP5 = True
NUMBER_OF_ERRORS_MAX = 10
name_of_dictionaries = {
"en": "english.lg",
"fr": "french.lg",
"ru": "russian.lg"
}
# ------------------------------------------------------------------------------------------------------
# BASIC FONCTIONS
def isValidLanguage(language):
"""
Vérifie si la langue donnée en paramètre fait partie de la liste des langues autorisées.
:param language: la langue à vérifier
:type language: str
:return: le résultat du test
:rtype: bool
"""
global name_of_dictionaries
if type(language) != str or len(language) != 2:
return False
return language in name_of_dictionaries.keys()
def is_number_of_errors_correct(nb_errors):
"""
Vérifie si le nombre d'erreurs passé en paramètre est valide.
Args:
nb_errors (int): Le nombre d'erreurs à vérifier.
Returns:
bool: True si le nombre d'erreurs est valide, False sinon.
"""
global NUMBER_OF_ERRORS_MAX
return 0 <= nb_errors <= NUMBER_OF_ERRORS_MAX
assert type(nb_errors) == int, "le nombre d'erreurs à tester n'est pas un entier"
def get_list_of_letters_possibles(language="en"):
"""
Return a list of possible letters according to the selected language.
:param language: the name of the language (default is 'en' for English)
:type language: str
:return: the list of possible letters
:rtype: list
"""
assert isValidLanguage(language), "Invalid language"
if language == "en":
letters = "abcdefghijklmnopqrstuvwxyz"
elif language == "fr":
letters = "abcdefghijklmnopqrstuvwxyzàâéèêëîïôùûüÿç"
elif language == "ru":
letters = "абвгдеёжзийклмнопрстуфхцчшщъыьэюя"
else:
letters = ""
return list(letters)
def is_letter(variable, language="en"):
"""
Returns True if the input variable is a valid letter in the given language.
Args:
variable (str): The variable to check.
language (str): The language to use. Currently only supports "en" for English.
Returns:
bool: True if the input variable is a valid letter, False otherwise.
"""
valid_letters = set("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
if variable in valid_letters:
return True
else:
return False
"""
Test if a particular letter (string) is correct in a specific language
:param variable: the variable to check
:type variable: X
:param language: the name of the language in which we need to check the letter
:type language: str
:return: the result of the test
:rtype: bool
"""
assert isValidLanguage(language), "la langue n'est pas valide"
pass
def is_a_letter_list(variable, language="en"):
"""
Returns True if the input variable is a list of valid letters in the given language.
Args:
variable (list): The variable to check.
language (str): The language to use. Currently only supports "en" for English.
Returns:
bool: True if the input variable is a list of valid letters, False otherwise.
"""
for letter in variable:
if not is_letter(letter, language):
return False
return True
"""
Test if a variable is a list of letters (string) in a specific language
:param variable:
:type variable:
:param language: the name of the language in which we need to check the letter
:type language: str
:return:
:rtype:
"""
assert isValidLanguage(language), "la langue n'est pas valide"
pass
def is_a_mask(variable):
"""
Vérifie si une variable est un masque valide.
Args:
variable (any): la variable à vérifier
Returns:
bool: True si la variable est un masque valide, False sinon
"""
if not isinstance(variable, list): # Vérifie si la variable est une liste
return False
for element in variable:
if not isinstance(element, bool): # Vérifie si chaque élément de la liste est un booléen
return False
return True
"""
Test if a variable is a mask (a list of boolean)
:param variable: the variable to check
:type variable: X
:return: the result of the test
:rtype: bool
"""
pass
def is_a_frequency(variable):
"""
Test if a variable is a frequency (float between 0.0 and 100.0)
:param variable: the variable to check
:type variable: X
:return: the result of the test
:rtype: bool
"""
pass
def is_a_dictionnary_of_frequencies(variable, language="en"):
"""
Test if a variable is a dictionnary of frequencies (float between 0.0 and 100.0)
with as indices the letters
:param variable: the variable to check
:type variable: X
:param language: the name of the language in which we need to check the dictionnary of frequencies
:type language: str
:return: the result of the test
:rtype: bool
"""
assert isValidLanguage(language), "la langue n'est pas valide"
pass
# ------------------------------------------------------------------------------------------------------
def read_dictionary_file(name_file):
"""
Read the file name_file and extract each word one per ligne and export it as a list of words
:param name_file: name of the file with words
:type name_file: str
:return: list of string (words)
:rtype: list
raise an FileNotFoundError if the file doesn\'t exist
raise an ValueError if the list of words is empty
"""
if not os.path.exists("./resources/"+name_file) or not os.path.isfile("./resources/"+name_file):
raise FileNotFoundError("Le fichier "+name_file+" n\'est pas présent dans le répertoire resources/")
list_of_words = []
file = open("./resources/"+name_file, "r", encoding="utf8")
for ligne in file.readlines():
word = ligne.split("\n")[0]
list_of_words.append(word)
file.close()
if len(list_of_words) == 0:
raise ValueError("Le fichier "+name_file+" dans le répertoire resources/ est vide.")
return list_of_words
def pick_a_word(list_of_words):
"""
Choose a random word from a list of words
:param list_of_words: an not empty list of the words
:type list_of_words: list<str>
:return: a word picked randomly from the list
:rtype: str
raise an TypeError if list_of_words is not a list of string or if the list is empty
raise an ValueError if the word picked is empty
"""
if type(list_of_words) != list or any([type(list_of_words[i]) != str for i in range(len(list_of_words))]):
raise TypeError("La liste de mots n\'est pas du bon type.")
if len(list_of_words) == 0:
raise TypeError("La liste de mots est vide.")
indice_word = random.randint(0, len(list_of_words)-1)
word = list_of_words[indice_word]
if len(word) == 0:
raise ValueError("Le mot a l\'indice "+str(indice_word)+" est vide.")
return word
def convert_string_to_char_list(word):
"""
Converts a word represented as a string into a list of characters.
Args:
word (str): The word to convert.
Returns:
list: A list of characters representing the input word.
Raises:
ValueError: If the input word is an empty string or contains invalid characters.
"""
if not isinstance(word, str):
raise TypeError("Input must be a string")
if not word:
raise ValueError("Input string cannot be empty")
char_list = []
for i in range(len(word)):
if not is_letter(word[i]):
raise ValueError(f"Invalid character '{word[i]}' in input string")
char_list.append(word[i])
if not is_a_letter_list(char_list):
raise ValueError("Input string contains non-letter characters")
return char_list
"""
Convert a word to a list of characters
:param word: the word to convert
:type word: str
:return: the list of each characters of the word
:rtype: list<str>
"""
pass
def ask_for_a_letter(language="en"): #base et (IMP2)
"""
Asks the user to input a valid letter between 'A' and 'Z'.
Args:
language (str): The language to use. Currently only supports "en" for English.
Returns:
str: The valid letter input by the user.
Raises:
ValueError: If the input is not a valid letter between 'A' and 'Z'.
"""
valid_letters = set("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
while True:
letter = input("Please enter a valid letter between A and Z: ").strip().upper()
if letter in valid_letters:
return letter
else:
raise ValueError("Invalid input. Please enter a valid letter between A and Z.")
#base et (IMP2)z
#def ask_for_a_letter(list_of_letters_picked, language="en"): #(IMP1)
#def ask_for_a_letter(list_of_letters_picked, list_of_letters_possibles, language="en"): #(IMP1, IMP3)
"""
Ask a letter to the user and check if the letter is valid and not previously asked
:param list_of_letters_picked:
:type list_of_letters_picked:
:param list_of_letters_possibles:
:type list_of_letters_possibles:
:param language: the language in which we need to ask the letter to the user
:type language: str
:return:
:rtype:
"""
assert isValidLanguage(language), "la langue n'est pas valide"
#(IMP1)
#assert ...
#------
#(IMP3)
#assert ...
#------
pass
def display_word(word, mask, language="en"):
# Vérification des pré-conditions
assert isinstance(word, list) and len(word) > 0, "Le mot doit être une liste non vide"
assert isinstance(mask, list) and len(mask) == len(word), "Le masque doit être une liste de booléens de même longueur que le mot"
assert isinstance(language, str) and len(language) == 2, "La langue doit être une chaîne de 2 caractères représentant une langue prise en charge par le programme"
# Affichage du mot avec le masque
display_word = ""
for i in range(len(word)):
if mask[i]:
display_word += word[i] + " "
else:
display_word += "? "
print("Mot à trouver : " + display_word)
"""
Display the word showing only the letters found, in a specific language
:param word: a list with all the letters to find
:type word: list<str>
:param mask: a list with bool indicating if a letter if found or not
:type mask: list<bool>
:param language: the language in which we need to display the word
:type language: str
:return: -
:rtype: None
"""
assert isValidLanguage(language), "la langue n'est pas valide"
#assert ...
pass
def is_letter_in_word(word, letter, language="en"):
"""
Vérifie si une lettre est présente dans un mot dans une langue donnée.
Args:
word (str): le mot dans lequel on cherche la lettre
letter (str): la lettre à chercher
language (str): la langue dans laquelle le mot et la lettre sont représentés (par défaut en anglais)
Returns:
bool: True si la lettre est présente dans le mot, False sinon
"""
# Vérifie si le mot et la lettre sont valides
assert is_a_word(word, language), "Le mot est invalide."
assert is_a_letter(letter, language), "La lettre est invalide."
# Recherche la lettre dans le mot
return letter in word
"""
:param word:
:type word:
:param letter:
:type letter:
:param language: the language in which we need to check the letter
:type language:
:return:
:rtype:
"""
assert isValidLanguage(language), "la langue n'est pas valide"
#assert ...
pass
def get_mask(word, language="en"):
"""
Retourne le masque associé à un mot dans une langue donnée.
Args:
word (str): le mot dont on veut le masque
language (str): la langue dans laquelle le mot est représenté (par défaut en anglais)
Returns:
list: le masque associé au mot
"""
# Vérifie si le mot est valide
assert is_a_word(word, language), "Le mot est invalide."
# Convertit le mot en tableau de caractères
word_list = convert_string_to_char_list(word)
# Initialise le masque à False pour chaque lettre du mot
mask = [False] * len(word_list)
return mask
"""
:param word:
:type word:
:param language:
:type language:
:return:
:rtype:
"""
# in the mask if the letter is found the value at the indice i will be True, False if not
assert isValidLanguage(language), "la langue n'est pas valide"
pass
def update_mask(word, mask, letter_to_reveal, language="en"):
"""
Update the mask for a word in a specific language
:param word:
:type word:
:param mask:
:type mask:
:param letter_to_reveal:
:type letter_to_reveal:
:param language:
:type language:
:return:
:rtype:
"""
assert isValidLanguage(language), "la langue n'est pas valide"
#assert ...
pass
def is_game_finished(mask, nb_errors):
"""
Vérifie si le jeu est terminé en fonction du masque et du nombre d'erreurs.
Args:
mask (List[bool]): Le masque représentant les lettres trouvées et manquantes.
nb_errors (int): Le nombre d'erreurs commises par le joueur.
Returns:
bool: True si le jeu est terminé, False sinon.
"""
assert isinstance(mask, list), "Le masque doit être une liste de booléens."
assert isinstance(nb_errors, int), "Le nombre d'erreurs doit être un entier."
assert is_number_of_errors_correct(nb_errors), f"Le nombre d'erreurs doit être compris entre 0 et {NUMBER_OF_ERRORS_MAX}."
if nb_errors >= NUMBER_OF_ERRORS_MAX:
return True
if False not in mask:
return True
return False
#assert
pass
# --- IMPROVEMENTS ---
def menu_choose_a_language(): #(IMP3)
"""
Show a menu to the user and return the language selected
:return: the language selected ('fr', 'en', 'ru')
:rtype: str
"""
global name_of_dictionaries
pass
def change_lowercase_to_uppercase(letter, language="en"): #(IMP2)
"""
TO DO
"""
assert isValidLanguage(language), "la langue n'est pas valide"
pass
def get_frequencies_of_letters_in_language(language="en"): #(IMP3, IMP4)
"""
Return a the frequencies of the letters in a particular language given in parameter
:param language: the language in which we need to generate the frequencies
:type language: str
:return: the frequencies of the letters
:rtype: dict<str, float>
"""
assert isValidLanguage(language), "la langue n'est pas valide"
frequence_fr = {}
frequence_en = {}
frequence_ru = {}
#TO COMPLETE
pass
def get_values(x):
"""
Return the second value of a 2-uplets
:param x: the 2_uplets
:type x: tuple<X>
:return: the second value of the 2_uplets
:rtype: X
"""
return x[1]
def recommend_next_letter(frequencies, list_of_letters_picked, language="en"): #(IMP3, IMP4)
"""
Return the second value of a 2-uplets
:param frequencies: the frequencies of the letters
:type frequencies: dict<str, float>
:param list_of_letters_picked: a list with all the previous letters asked
:type list_of_letters_picked: list<str>
:param language: the language in which we need to recommend the letter
:type language: str
:return: the letter recommended
:rtype: str
"""
#assert ...
pass
def display_hanged_man(nb_errors): #(IMP5)
"""
Display the hanged man in the console
:param nb_errors: the nb of errors
:type nb_errors: int
:return: -
:rtype: None
"""
pass
##################################################
if __name__ == "__main__":
# choice of the language and import of the dictionary
language = "en" #base
#language = ...() #(IMP3)
dictionary = read_dictionary_file(name_of_dictionaries[language])
# operation with language selected
#list_of_letters_possibles = get_list_of_letters_possibles(language) #(IMP4)
#frequencies = get_frequencies_of_letters_in_language(language) #(IMP4)
# choice of the word
word = pick_a_word(dictionary)
list_char = get_list_of_characters(word)
# initialisation
mask = initialize_mask(word)
nb_errors = 0
# initialisation of letters
#letters_picked = [] #(IMP1)
# loop over the game
while not is_game_finished(mask, nb_errors):
# display the current word
display_word(list_char, mask, language)
# display of the recommended letter (IMP4)
#recommend_letter = recommend_next_letter(frequencies, letters_picked, \
# language)
#print("Nous vous recommandons la lettre suivante :", recommend_letter)
# get the letter and update the list of letters_picked
letter = ask_for_a_letter(language) #base & (IMP2)
#letter = ask_for_a_letter(letters_picked, language) #(IMP1)
#letter = ask_for_a_letter(letters_picked, list_of_letters_possibles, \
#language)
#(IMP1, IMP3)
# update depending of the result of the test
isPresent = is_letter_in_word(list_char, letter, language)
# letters_picked.append(...)
# update the list of the letters picked #(IMP1)
if isPresent:
update_mask(list_char, mask, letter)
else:
nb_errors += 1
# display of the hangman
print("Il vous reste", NUMBER_OF_ERRORS_MAX - nb_errors, "erreurs disponibles.")
#display_hanged_man(nb_errors) #(IMP1)
print()
# display the current word
display_word(list_char, mask, language)
# display final result
if is_winning(mask):
print("\nVous avez gagné :)")
else:
print("\nVous avez perdu !!")
Afficher la suite