tinycodinglm / i18n /i18n-0014.jsonl
winapiadmin's picture
Upload folder using huggingface_hub (part 15)
b27bfb3 verified
|
Raw History Blame Contribute Delete
1.62 kB
opencode trace
System You are a helpful software engineer. Answer in the same language the user writes in, and give correct, minimal Python examples.

You are a helpful software engineer. Answer in the same language the user writes in, and give correct, minimal Python examples.

User

Comment lire/écrire du texte français (accents, cédille, ligatures œ/æ) en Python ?

Assistant

La cause la plus fréquente : ouvrir le fichier sans préciser encoding fait utiliser l'encodage du système (sous Windows, cp1252), et les octets UTF-8 sont mal interprétés (mojibake).

La bonne méthode :

  1. Indiquez toujours encoding="utf-8" en lecture comme en écriture.
  2. Pour un fichier d'origine inconnue, lisez avec encoding="utf-8-sig".
  3. Normalisez avec unicodedata.normalize("NFC", s) avant de comparer (é peut être précomposé ou décomposé).
  4. Les ligatures œ/æ ne se décomposent pas en NFC ; pour une comparaison insensible à la casse utilisez casefold() : "ŒUVRE".casefold() == "œuvre".
python
import unicodedata

TEXT = "Bonjour, monde ! Exemple : élève, garçon, cœur, naïve."

with open("fr.txt", "w", encoding="utf-8") as f:
    f.write(TEXT)

with open("fr.txt", "r", encoding="utf-8-sig") as f:
    data = f.read()

data = unicodedata.normalize("NFC", data)
print("Caractères :", len(data))
print("Comparaison :", "ŒUVRE".casefold() == "œuvre")
print(data)