{"type": "session", "harness": "opencode", "id": "i18n-0005", "name": "Korean text handling in Python"} {"type": "message", "message": {"role": "system", "content": "You are a helpful software engineer. Answer in the same language the user writes in, and give correct, minimal Python examples."}} {"type": "message", "message": {"role": "user", "content": "파이썬에서 한글 텍스트를 읽고 쓸 때 인코딩 문제를 피하려면 어떻게 해야 하나요? 코드 예제도 보여주세요."}} {"type": "message", "message": {"role": "assistant", "content": "가장 흔한 원인: `open()`에서 `encoding`을 지정하지 않으면 OS 기본 인코딩(Windows는 보통 cp949 계열)이 사용되어 UTF-8 바이트가 잘못 해독되고 깨집니다.\n\n올바른 방법:\n1. 읽기와 쓰기 모두 `encoding=\"utf-8\"`를 명시합니다.\n2. 출처가 불분명한 파일은 `encoding=\"utf-8-sig\"`로 읽습니다(BOM이 있으면 제거, 없으면 그대로).\n3. 비교 전에는 `unicodedata.normalize(\"NFC\", s)`로 정규화합니다. 특히 macOS는 한글을 자모(NFD)로 분리해 저장하므로, 정규화 없이 비교하면 같은 글자도 다르다고 나옵니다.\n4. `len()`은 코드 포인트 수이며, 바이트 수는 `len(s.encode(\"utf-8\"))`로 구합니다(한글 1자 = 3바이트).\n\n```python\nimport unicodedata\n\nTEXT = \"안녕하세요, 세계! 파이썬 한글 처리 예제입니다.\"\n\nwith open(\"ko.txt\", \"w\", encoding=\"utf-8\") as f:\n f.write(TEXT)\n\nwith open(\"ko.txt\", \"r\", encoding=\"utf-8-sig\") as f:\n data = f.read()\n\nnfc = unicodedata.normalize(\"NFC\", data)\nnfd = unicodedata.normalize(\"NFD\", data)\nprint(\"문자 수(NFC):\", len(nfc))\nprint(\"문자 수(NFD):\", len(nfd)) # 자모 분리로 더 길어짐\nprint(\"동일 여부:\", nfc == unicodedata.normalize(\"NFC\", TEXT))\n```"}}