File size: 2,477 Bytes
b27bfb3
 
 
 
1
2
3
4
5
{"type": "session", "harness": "opencode", "id": "i18n-0011", "name": "Thai 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": "ใน Python จะอ่านและเขียนข้อความภาษาไทยอย่างไรไม่ให้อักขระเสีย? ขอตัวอย่างโค้ดด้วย"}}
{"type": "message", "message": {"role": "assistant", "content": "สาเหตุที่พบบ่อยที่สุด: เปิดไฟล์โดยไม่ระบุ `encoding` Python จะใช้ encoding เริ่มต้นของระบบ (บน Windows มักเป็น cp874) ทำให้ไบต์ UTF-8 ถูกถอดรหัสผิด กลายเป็น mojibake\n\nวิธีที่ถูกต้อง:\n1. ระบุ `encoding=\"utf-8\"` ทุกครั้งทั้งตอนอ่านและเขียน\n2. ไฟล์ที่ไม่รู้ที่มา ให้อ่านด้วย `encoding=\"utf-8-sig\"` — มี BOM ก็ตัดออก ไม่มีก็อ่านได้ปกติ\n3. ภาษาไทยไม่มีช่องว่างระหว่างคำ (ช่องว่างใช้แบ่งวลี/ประโยค) อย่าตัดคำด้วย `split(\" \")` แล้วหวังผลแบบภาษาอังกฤษ\n4. สระบนล่างและวรรณยุกต์เป็น combining marks — `len()` นับ code point ไม่ใช่รูปอักขระที่เห็น เปรียบเทียบสตริงให้ normalize เป็น NFC ก่อน\n\n```python\nimport unicodedata\n\nTEXT = \"สวัสดีชาวโลก! ตัวอย่างการประมวลผลข้อความภาษาไทย\"\n\nwith open(\"th.txt\", \"w\", encoding=\"utf-8\") as f:\n    f.write(TEXT)\n\nwith open(\"th.txt\", \"r\", encoding=\"utf-8-sig\") as f:\n    data = f.read()\n\ndata = unicodedata.normalize(\"NFC\", data)\nprint(\"code points:\", len(data))\nprint(\"bytes:\", len(data.encode(\"utf-8\")))\nprint(data)\n```"}}