pythonÄ£¿éÖ®codecs
python¶Ô¶à¹úÓïÑԵĴ¦ÀíÊÇÖ§³ÖµÄºÜºÃµÄ£¬Ëü¿ÉÒÔ´¦ÀíÏÖÔÚÈÎÒâ±àÂëµÄ×Ö·û£¬ÕâÀïÉîÈëµÄÑо¿Ò»ÏÂpython¶Ô¶àÖÖ²»Í¬ÓïÑԵĴ¦Àí¡£
ÓÐÒ»µãÐèÒªÇå³þµÄÊÇ£¬µ±pythonÒª×ö±àÂëת»»µÄʱºò£¬»á½èÖúÓÚÄÚ²¿µÄ±àÂ룬ת»»¹ý³ÌÊÇÕâÑùµÄ£º
ÔÓбàÂë -> ÄÚ²¿±àÂë ->
Ä¿µÄ±àÂë
pythonµÄÄÚ²¿ÊÇʹÓÃunicodeÀ´´¦ÀíµÄ£¬µ«ÊÇunicodeµÄʹÓÃÐèÒª¿¼ÂǵÄÊÇËüµÄ±àÂë¸ñʽÓÐÁ½ÖÖ£¬Ò»ÊÇUCS-2£¬ËüÒ»¹²ÓÐ65536¸öÂë
룬ÁíÒ»ÖÖÊÇUCS-4£¬ËüÓÐ2147483648g¸öÂëλ¡£¶ÔÓÚÕâÁ½ÖÖ¸ñʽ£¬python¶¼ÊÇÖ§³ÖµÄ£¬Õâ¸öÊÇÔÚ±àÒëʱͨ¹ý--enable-
unicode=ucs2»ò--enable-unicode=ucs4À´Ö¸¶¨µÄ¡£ÄÇôÎÒÃÇ×Ô¼ºÄ¬ÈÏ°²×°µÄpythonÓеÄʲô±àÂëÔõôÀ´È·¶¨ÄØ£¿ÓÐÒ»¸ö
°ì·¨£¬¾ÍÊÇͨ¹ýsys.maxunicodeµÄÖµÀ´Åжϣº
import
sys
print
sys.maxunicode
Èç¹ûÊä³öµÄֵΪ65535,ÄÇô¾ÍÊÇUCS-2,Èç¹ûÊä³öÊÇ1114111¾ÍÊÇUCS-4±àÂë¡£
ÎÒÃÇÒªÈÏʶµ½Ò»µã£ºµ±Ò»¸ö×Ö·û´®×ª»»ÎªÄÚ²¿±àÂëºó£¬Ëü¾Í²»ÊÇstrÀàÐÍÁË£¡ËüÊÇunicodeÀàÐÍ£º
a
=
"
·ç¾í²ÐÔÆ
"
print
type(a)
b
=
a.unicode(a,
"
gb2312
"
)
print
type(b)
Êä³ö£º
<type 'str'>
<type 'unicode'>
Õâ¸öʱºòb¿ÉÒÔ·½±ãµÄÈÎÒâת»»ÎªÆäËû±àÂ룬±ÈÈçת»»Îªutf-8:
c
=
b.encode(
"
utf-8
"
)
print
c
cÊä³öµÄ¶«Î÷¿´ÆðÀ´ÊÇÂÒÂ룬ÄǾͶÔÁË£¬ÒòΪÊÇutf-8µÄ×Ö·û´®¡£
ºÃÁË£¬¸Ã˵˵codecsÄ£¿éÁË£¬ËüºÍÎÒÉÏÃæ˵µÄ¸ÅÄîÊÇÃÜÇÐÏà¹ØµÄ¡£codecsרÃÅÓÃ×÷±àÂëת»»£¬µ±È»£¬Æäʵͨ¹ýËüµÄ½Ó¿ÚÊÇ¿ÉÒÔÀ©Õ¹µ½ÆäËû¹ØÓÚ´úÂë·½Ãæ
µÄת»»µÄ£¬Õâ¸ö¶«Î÷ÕâÀï²»Éæ¼°¡£
#
-*- encoding: gb2312 -*-
import
codecs, sys
print
'
-
'
*
60
#
´´½¨gb2312±àÂëÆ÷
look
=
codecs.lookup(
"
gb2312
"
)
#
´´½¨utf-8±àÂëÆ÷
look2
=
codecs.lookup(
"
utf-8
"
)
a
=
"
ÎÒ°®±±¾©
"
print
len(a), a
#
°Ña±àÂëΪÄÚ²¿µÄunicode, µ«ÎªÊ²Ã´·½·¨ÃûΪdecodeÄØ£¬ÎÒ
µÄÀí½âÊÇ°Ñgb2312µÄ×Ö·û´®½âÂëΪunicode
b
=
look.de
Ïà¹ØÎĵµ£º
Ç°ÑÔ£º
×î½üÓÖÏëѧϰpython,ÓÖÏëÈ¥ÎÂÏ°Ò»ÏÂËã·¨£¬ÓÚÊǾÍÏë³öÁËÕâ¸öÁ½²»ÎóµÄ·½·¨,^_^
¶ÑÕ»£º
ʹÓÃpythonµÄÁбí½á¹¹£¬ÏêÇé¿ÉÒԲ鿴help(list)
#Filename: stack.py
shoplist=['apple','mango','carrot','banana']
shoplist.append('rice')
popitem=shoplist[-1]
del shoplist[-1]
print 'the popitem is',popitem
......
ÕÛÌÚ¼ÆËã»ú£¬±»¼ÆËã»úÕÛÌÚ£¬Ç°Ç°ºóºóÒ²ÓÐÊ®¼¸Äê¡£
×î¿É±¯µÄÊǾÓȻһÎÞËù³É£¬ËäÈ»½ö½ö³öÓÚÐËȤ£¬²¢ÎÞ¹¤×÷֮ѹÁ¦£¬µ«ÊÇÕâÖÖ´ìÕÛ¸ÐȷʵÊÇʵ´òʵµÄ¡£
ÒѾ¼Ç²»ÆðÊÇÄÄÒ»ÌìÁË£¬ºÃÏñͻȻ¾ÍÖªµÀÁËpythonµÄ´æÔÚ£¬´Ó×î³õµÄ²»¾Ò⣬µ½Ô½À´Ô½Ï²°®£¬ÎÒÒ»²½²½µÄÏòpython¿¿½ü¡£
ÎÒϲ»¶Python£¬ÕâÊÇÒ»¸öÊÂʵ£¬ÎÒ׫´ ......
python
ÓïÑÔ¸ÅÀÀ
python
½Å±¾¿ÉÒÔ´¦ÀíÍⲿ´«½øÀ´µÄ²ÎÊý ¼´sys.argv[]
£¬argv[]
µÄʹÓÃÓëlinux
ÏÂÏàͬ
python
±¾ÉíÊǽâÊÍÓïÑÔ£¬¿ÉÒÔ¶ÔÊäÈëµÄʽ×ÓÇóÖµ¡£python
Ö§³ÖµÄ¶ÔÏóÈçÕûÊý¶¼ÊÇÁ¢¼´Êý£¬´ËÍâËûÖ§³Ö¸´Êý£¬¼°¶ÔËÄÔòÔËËã½âÊÍ¡£
ptyhon
Ö§³Ö×Ö·û´®£¬·ÅÔÚµ¥/
Ë«ÒýºÅÄÚ£¬×Ö·û´®ÊÇÊý×飬¿ÉÒÔͨ¹ý[i: ......
ÕýÔò±í´ïʽÊǸöħ¹í£¬Ò²ÊǸöÌìʹ¡£ÔÚÄãûÓÐÕÆÎÕËü֮ǰ£¬ËüÊÇħ¹í£¬ÔÚÄãÕÆÎÕËüºó£¬ËüÊÇÌìʹ£¬µ«ÊÇ£¬Ê±
²»Ê±»¹ÊÇÒªÌø³öÀ´£¬¸øÄãµ÷Ƥµ·µ°Ò»·¬¡£
Ò»¸öÕýÔò±í´ïʽ¾ÍÊÇÓÉÆÕͨ×Ö·ûÒÔ¼°ÌØÊâ×Ö·û×é³ÉµÄÎÄ×Öģʽ£¬¸ÃģʽÃèÊöÔÚ²éÕÒÎÄ×ÖÖ÷Ìåʱ´ý
Æ¥ÅäµÄÒ»¸ö»ò¶à¸ö×Ö·û´®¡£ÕýÔò±í´ïʽ×÷Ϊһ¸öÄ£°å£¬½«Ä³¸ö×Ö·ûģʽÓëËùËÑË÷µÄ ......
µ±ÎÒÃÇÕâÑù½¨Á¢Îļþʱ
f =
file('x1.txt', 'w')
f.write(u'ÖÐÎÄ')
f.colse()
Ö±
½Ó½á¹ûÓ¦¸ÃÊÇÀàËÆ
f.write(u'ÖÐÎÄ')
UnicodeEncodeError: 'ascii'
codec can't encode characters in position 0-16: ordinal not in
range(128)
ÒªÖ±½Óд utf-8 ÎļþÔõô°ìÄØ?
import codecs
f = codecs. ......