from datetime import timedeltaIn [33]: a = timedelta(days=2, hours=6)
In [34]: b = timedelta(hours=4.5)
In [35]: c = a + b
In [36]: c.days
Out[36]: 2
In [37]: c.seconds
Out[37]: 37800
In [38]: c.seconds/3600
Out[38]: 10.5
In [39]: c.total_seconds() / 3600
Out[39]: 58.5
Chap4 迭代器和生成器
手動訪問迭代器中的元素
with open('/etc/passwd') as f:try:while True:line = next(f)print(line, end='')except StopIteration:pass
def frange(start, stop, increment):x = startwhile x < stop:yield xx += increment
注意生成器只在響應迭代操作時才運行
對迭代器做切片操作
itertool.islice() 可以對迭代器和生成器做切片操作
In [3]: def count(n):...: while True:...: yield n...: n += 1...:
In [5]: c = count(0)
In [6]: c
Out[6]: <generator object count at 0x7f92899b3c80>
----> 1 c[0]
TypeError: 'generator' object has no attribute '__getitem__'import itertools
In [10]: for x in itertools.islice(c, 10, 20):...: print(x)
10
11
12
13
14
15
16
17
18
19
import gzip
with open('somefile.gz', 'rt') as f:text = f.read()import bz2
with open('somefile.bz2', 'rt') as f:text = f.read()import gzip
with open('somefile.gz', 'wt') as f:f.write(text)import bz2
with open('somefile.bz', 'wt') as f:f.write(text)
import pickle
data = ... #some python object
f = open('somefile', 'wb')
pickle.dump(data,f)
要將對象轉存為字符串,可以使用
import pickle
data = ... #some python object
f = open('somefile', 'wb')
pickle.dumps(data,f)
如果要從字節流中重新創建出對象,可以使用pickle.load()或者pickle.loads()
Chap 6 數據編碼與處理
讀寫JSON數據
主要使用JSON模塊
兩個主要的函數為json.dumps()和json.loads()
如果是文件而不是字符串的話使用json.dump()和json.load()
解析簡單的XML文檔
xml.etree.ElementTree可以從簡單的XML文檔中提取數據
from urllib.request import urlopen
from xml.etree.ElementTree import parseu = urlopen('http://planet.python.org/rss20.xml')
doc = parse(u)
In [24]: for item in doc.iterfind('channel/item'):....: title = item.findtext('title')....: date = item.findtext('pubDate')....: link = item.findtext('link')....: print (title)....: print(date)....: print(link)....: print()....: