tinycodinglm / i18n /i18n-0007.jsonl
winapiadmin's picture
Upload folder using huggingface_hub (part 15)
b27bfb3 verified
|
Raw History Blame Contribute Delete
2.36 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

पायथन में हिंदी (देवनागरी) टेक्स्ट को सही से कैसे पढ़ें और लिखें? कोड उदाहरण भी दें।

Assistant

सबसे आम कारण: open() में encoding न बताने पर Python OS की डिफ़ॉल्ट एन्कोडिंग इस्तेमाल करता है (Windows पर अक्सर cp1252), जिससे UTF-8 बाइट गलत पढ़े जाते हैं और अजीब अक्षर (mojibake) दिखते हैं।

सही तरीका:

  1. पढ़ते और लिखते समय हमेशा encoding="utf-8" लिखें।
  2. अनजान स्रोत की फ़ाइल encoding="utf-8-sig" से पढ़ें — BOM हो तो हट जाता है, न हो तो कोई असर नहीं।
  3. तुलना से पहले unicodedata.normalize("NFC", s) से सामान्यीकृत करें (मात्राओं और संयुक्ताक्षरों के कारण)।
  4. len(s) कोड पॉइंट गिनता है, अक्षर-समूह नहीं; बाइट चाहिए तो len(s.encode("utf-8")) लें।
python
import unicodedata

TEXT = "नमस्ते दुनिया! पायथन में हिंदी टेक्स्ट का उदाहरण।"

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

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

data = unicodedata.normalize("NFC", data)
print("अक्षर (कोड पॉइंट):", len(data))
print("बाइट्स:", len(data.encode("utf-8")))
print(data)