python enumerateÓ÷¨
python cookbook
Recipe 2.5. Counting Lines in a File
£¬
½ñÈÕ·¢ÏÖÒ»¸öк¯Êý
enumerate
¡£Ò»°ãÇé¿ö϶ÔÒ»¸öÁбí»òÊý×é¼ÈÒª±éÀúË÷ÒýÓÖÒª±éÀúÔªËØÊ±£¬»áÕâÑùд£º
for
i
in
range
(0
,
len
(list
)):
print
i
,
list
[
i
]
µ«ÊÇÕâÖÖ·½·¨ÓÐЩÀÛ׸£¬Ê¹ÓÃ
ÄÚÖÃenumerrateº¯Êý»áÓиü¼ÓÖ±½Ó£¬ÓÅÃÀµÄ×ö·¨£¬ÏÈ¿´¿´enumerateµÄ¶¨Ò壺
def
enumerate
(collection
):
'Generates an indexed series:
(0,coll[0]), (1,coll[1]) ...'
i
=
0
it
=
iter
(collection
)
while
1
:
yield
(i
,
it
.
next
())
i
+=
1
enumerate»á½«Êý×é»òÁбí×é³ÉÒ»¸öË÷ÒýÐòÁС£Ê¹ÎÒÃÇÔÙ»ñÈ¡Ë÷ÒýºÍË÷ÒýÄÚÈݵÄʱºò¸ü¼Ó·½±ãÈçÏ£º
for
index
£¬
text
in
enumerate
(list
)):
print
index
,
text
ÔÚ
cookbookÀï½éÉÜ£¬Èç¹ûÄãÒª¼ÆËãÎļþµÄÐÐÊý£¬¿ÉÒÔÕâÑùд£º
count
=
len
(open
(thefilepath
,
‘
rU
’
).
readlines
())
Ç°ÃæÕâÖÖ·½·¨¼òµ¥£¬µ«ÊÇ¿ÉÄܱÈ
½ÏÂý£¬µ±Îļþ±È½Ï´óʱÉõÖÁ²»Äܹ¤×÷£¬ÏÂÃæÕâÖÖÑ»·¶ÁÈ¡µÄ·½·¨¸üºÏÊÊЩ¡£
Count
=
-
1
For
count
,
line
in
enumerate
(open
(thefilepath
,
‘
rU
’
))£º
Pass
Count
+=
1
Ïà¹ØÎĵµ£º
µ±ÎÒÃÇÕâÑù½¨Á¢Îļþʱ
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. ......
python¶Ô¶à¹úÓïÑԵĴ¦ÀíÊÇÖ§³ÖµÄºÜºÃµÄ£¬Ëü¿ÉÒÔ´¦ÀíÏÖÔÚÈÎÒâ±àÂëµÄ×Ö·û£¬ÕâÀïÉîÈëµÄÑо¿Ò»ÏÂpython¶Ô¶àÖÖ²»Í¬ÓïÑԵĴ¦Àí¡£
ÓÐÒ»µãÐèÒªÇå³þµÄÊÇ£¬µ±pythonÒª×ö±àÂëת»»µÄʱºò£¬»á½èÖúÓÚÄÚ²¿µÄ±àÂ룬ת»»¹ý³ÌÊÇÕâÑùµÄ£º
ÔÓбàÂë -> ÄÚ²¿±àÂë ->
Ä¿ ......
>>> import time
>>> import datetime
>>>
now = time.localtime()
>>> now
(2006, 4, 30, 18, 7, 35,
6, 120, 0)
>>> type(now)
<type 'time.struct_time'>
>>>
str_now = time.strftime("%m/%d/%Y %X", now )
>>>
str_n ......
“¹þ¹þ£¡ÖªµÀÎÒ²Ù×÷Ö®ÍõС°×µÄÀ÷º¦Á˰ɣ¡”
ÿµ±ÖÜÁùÍíÉÏ£¬Ð¡°××ÜÊÇÒª¸úËÞÉáµÄµÜÐÖÌô¼¸¾ÖħÊÞ¡£Æ¾½è×Å·çɧµÄ×ßλºÍâ«ËöµÄÒâʶ£¬Ð¡°××ÜÊÇЦµÀ×îºó¡£Õâ²»£¬Ð¡°×ÓÖÒ»´ÎÈ¡µÃÁËÒÔÒ»µÐ¶þµÄʤÀû¡£
“Ö÷ÒªÊǶàÏß²Ù×÷£¡”ÕâÊÇС°×¶Ô×Ô¼ºÊ¤ÀûµÄ×ܽ ......
def
subString
(s,
length):
us = unicode(s, 'utf-8
')
gs =
us.encode('gb2312
')
n = int(length)
t = gs[:n]
while True
:
try
:
&nb ......