2010-05-18 7 views
9

में यूनिकोड के रूप में बच निकले स्ट्रिंग को दिखाएं, मुझे कुछ दिनों के लिए पाइथन पता है। यूनिकोड पाइथन के साथ एक समस्या प्रतीत होता है।पाइथन

मैं इस

'\u0110\xe8n \u0111\u1ecf n\xfat giao th\xf4ng Ng\xe3 t\u01b0 L\xe1ng H\u1ea1' 

की तरह एक पाठ स्ट्रिंग एक पाठ फ़ाइल भंडार है मैं फ़ाइल को पढ़ने और स्ट्रिंग प्रिंट कर सकते हैं, लेकिन यह गलत तरीके से प्रदर्शित करता है। कैसे मैं इसे प्रिंट पालन सही ढंग से स्क्रीन करने के लिए कर सकते हैं:

"Đèn đỏ nút giao thông Ngã tư Láng Hạ" 

अग्रिम धन्यवाद

+1

"स्ट्रिंग प्रिंट करें" द्वारा, क्या आप कंसोल का मतलब रखते हैं? यदि ऐसा है, तो शायद यह आपका कंसोल है कि समस्या है - क्या आप वाकई यूनिकोड वर्णों का समर्थन करते हैं? –

उत्तर

0

इस

>>> s=u"\u0110\xe8n \u0111\u1ecf n\xfat giao th\xf4ng Ng\xe3 t\u01b0 L\xe1ng H\u1ea1" 
>>> print s 
=> Đèn đỏ nút giao thông Ngã tư Láng Hạ 
8
>>> x=r'\u0110\xe8n \u0111\u1ecf n\xfat giao th\xf4ng Ng\xe3 t\u01b0 L\xe1ng H\u1ea1' 
>>> u=unicode(x, 'unicode-escape') 
>>> print u 
Đèn đỏ nút giao thông Ngã tư Láng Hạ 

इस में एक मैक है, जहां Terminal.App ठीक से काम करता प्रयास करें sys.stdout.encoding को utf-8 पर सेट किया गया है। अपने मंच को सही ढंग से (या बिल्कुल) उस गुण निर्धारित नहीं करता है, तो आप

print u.decode('utf8') 

या कोई अन्य अपने टर्मिनल एन्कोडिंग/कंसोल का उपयोग कर रहा है के साथ अंतिम पंक्ति को बदलने के लिए की आवश्यकता होगी।

ध्यान दें कि पहली पंक्ति में मैं कच्चे स्ट्रिंग को शाब्दिक रूप से असाइन करता हूं ताकि "बचने के अनुक्रम" का विस्तार नहीं किया जा सके - यह केवल नकल करता है कि क्या होगा यदि x को (पाठ या बाइनरी) फ़ाइल से पढ़ा जा रहा था वह शाब्दिक सामग्री।

1

यह कोड और आउटपुट के साथ एक सरल उदाहरण दिखाने में मदद करता है जो आपने स्पष्ट रूप से प्रयास किया है। एक अनुमान में आपका कंसोल वियतनामी का समर्थन नहीं करता है। यहां कुछ विकल्प दिए गए हैं:

# A byte string with Unicode escapes as text. 
>>> x='\u0110\xe8n \u0111\u1ecf n\xfat giao th\xf4ng Ng\xe3 t\u01b0 L\xe1ng H\u1ea1' 

# Convert to Unicode string. 
>>> x=x.decode('unicode-escape') 
>>> x 
u'\u0110\xe8n \u0111\u1ecf n\xfat giao th\xf4ng Ng\xe3 t\u01b0 L\xe1ng H\u1ea1' 

# Try to print to my console: 
>>> print x 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "C:\dev\python\lib\encodings\cp437.py", line 12, in encode 
    return codecs.charmap_encode(input,errors,encoding_map) 
UnicodeEncodeError: 'charmap' codec can't encode character u'\u0110' in position 0: 
    character maps to <undefined> 

# My console's encoding is cp437. 
# Instead of the default strict error handling that throws exceptions, try: 
>>> print x.encode('cp437','replace') 
?èn ?? nút giao thông Ng? t? Láng H?  

# Six characters weren't supported. 
# Here's a way to write the text to a temp file and display it with another 
# program that supports the UTF-8 encoding: 
>>> import tempfile 
>>> f,name=tempfile.mkstemp() 
>>> import os 
>>> os.write(f,x.encode('utf8')) 
48 
>>> os.close(f) 
>>> os.system('notepad.exe '+name) 

आशा है कि आपकी मदद करता है।