File size: 1,892 Bytes
b27bfb3 | 1 2 3 4 5 | {"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```"}}
|