Skip to content

Commit 145a1c6

Browse files
committed
6.1小节完成
1 parent af589ff commit 145a1c6

5 files changed

Lines changed: 246 additions & 9 deletions

File tree

‎cookbook/c06/__init__.py‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
#!/usr/bin/env python
2+
# -*- encoding: utf-8 -*-
3+
"""
4+
Topic: sample
5+
Desc :
6+
"""
7+

‎cookbook/c06/p01_rw_csv.py‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
#!/usr/bin/env python
2+
# -*- encoding: utf-8 -*-
3+
"""
4+
Topic: 读写CSV数据
5+
Desc :
6+
"""
7+
import csv
8+
from collections import namedtuple
9+
10+
11+
def rw_csv():
12+
with open('stocks.csv') as f:
13+
f_csv = csv.reader(f)
14+
headers = next(f_csv)
15+
for row in f_csv:
16+
print(row)
17+
18+
with open('stocks.csv') as f:
19+
f_csv = csv.reader(f)
20+
headings = next(f_csv)
21+
Row = namedtuple('Row', headings)
22+
for r in f_csv:
23+
row = Row(*r)
24+
# Process row
25+
print(row.Change)
26+
27+
headers = ['Symbol', 'Price', 'Date', 'Time', 'Change', 'Volume']
28+
rows = [('AA', 39.48, '6/11/2007', '9:36am', -0.18, 181800),
29+
('AIG', 71.38, '6/11/2007', '9:36am', -0.15, 195500),
30+
('AXP', 62.58, '6/11/2007', '9:36am', -0.46, 935000),
31+
]
32+
33+
with open('stocks.csv', 'w') as f:
34+
f_csv = csv.writer(f)
35+
f_csv.writerow(headers)
36+
f_csv.writerows(rows)
37+
38+
39+
if __name__ == '__main__':
40+
rw_csv()
41+

‎cookbook/c06/stocks.csv‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
Symbol,Price,Date,Time,Change,Volume
2+
AA,39.48,6/11/2007,9:36am,-0.18,181800
3+
AIG,71.38,6/11/2007,9:36am,-0.15,195500
4+
AXP,62.58,6/11/2007,9:36am,-0.46,935000

‎source/c06/p01_read_write_csv_data.rst‎

Lines changed: 191 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,14 +5,202 @@
55
----------
66
问题
77
----------
8-
todo...
8+
你想读写一个CSV格式的文件。
9+
10+
|
911
1012
----------
1113
解决方案
1214
----------
13-
todo...
15+
对于大多数的CSV格式的数据读写问题,都可以使用 ``csv`` 库。、
16+
例如,假设你在一个名叫stocks.csv文件中有一些股票市场数据,就像这样:
17+
18+
.. code-block:: python
19+
20+
Symbol,Price,Date,Time,Change,Volume
21+
"AA",39.48,"6/11/2007","9:36am",-0.18,181800
22+
"AIG",71.38,"6/11/2007","9:36am",-0.15,195500
23+
"AXP",62.58,"6/11/2007","9:36am",-0.46,935000
24+
"BA",98.31,"6/11/2007","9:36am",+0.12,104800
25+
"C",53.08,"6/11/2007","9:36am",-0.25,360900
26+
"CAT",78.29,"6/11/2007","9:36am",-0.23,225400
27+
28+
下面向你展示如何将这些数据读取为一个元组的序列:
29+
30+
.. code-block:: python
31+
32+
import csv
33+
with open('stocks.csv') as f:
34+
f_csv = csv.reader(f)
35+
headers = next(f_csv)
36+
for row in f_csv:
37+
# Process row
38+
...
39+
40+
在上面的代码中,``row`` 会是一个元组。因此,为了访问某个字段,你需要使用下标,如row[0]访问Symbol,
41+
row[4]访问Change。
42+
43+
由于这种下标访问通常会引起混淆,你可以考虑使用命名元组。例如:
44+
45+
.. code-block:: python
46+
47+
from collections import namedtuple
48+
with open('stock.csv') as f:
49+
f_csv = csv.reader(f)
50+
headings = next(f_csv)
51+
Row = namedtuple('Row', headings)
52+
for r in f_csv:
53+
row = Row(*r)
54+
# Process row
55+
...
56+
57+
它允许你使用列名如 ``row.Symbol`` 和 ``row.Change`` 代替下标访问。
58+
需要注意的是这个只有在列名是合法的Python标识符的时候才生效。如果不是的话,
59+
你可能需要修改下原始的列名(如将非标识符字符替换成下划线之类的)。
60+
61+
另外一个选择就是将数据读取到一个字典序列中去。可以这样做:
62+
63+
.. code-block:: python
64+
65+
import csv
66+
with open('stocks.csv') as f:
67+
f_csv = csv.DictReader(f)
68+
for row in f_csv:
69+
# process row
70+
...
71+
72+
In this version, you would access the elements of each row using the row headers. For
73+
example, row['Symbol'] or row['Change'].
74+
在这个版本中,你可以使用列名去访问每一行的数据了。比如,``row['Symbol']`` 或者 ``row['Change']`` 。
75+
76+
为了写入CSV数据,你仍然可以使用csv模块,不过这时候先创建一个 ``writer`` 对象。例如;
77+
78+
.. code-block:: python
79+
80+
headers = ['Symbol','Price','Date','Time','Change','Volume']
81+
rows = [('AA', 39.48, '6/11/2007', '9:36am', -0.18, 181800),
82+
('AIG', 71.38, '6/11/2007', '9:36am', -0.15, 195500),
83+
('AXP', 62.58, '6/11/2007', '9:36am', -0.46, 935000),
84+
]
85+
86+
with open('stocks.csv','w') as f:
87+
f_csv = csv.writer(f)
88+
f_csv.writerow(headers)
89+
f_csv.writerows(rows)
90+
91+
如果你有一个字典序列的数据,可以像这样做:
92+
93+
.. code-block:: python
94+
95+
headers = ['Symbol', 'Price', 'Date', 'Time', 'Change', 'Volume']
96+
rows = [{'Symbol':'AA', 'Price':39.48, 'Date':'6/11/2007',
97+
'Time':'9:36am', 'Change':-0.18, 'Volume':181800},
98+
{'Symbol':'AIG', 'Price': 71.38, 'Date':'6/11/2007',
99+
'Time':'9:36am', 'Change':-0.15, 'Volume': 195500},
100+
{'Symbol':'AXP', 'Price': 62.58, 'Date':'6/11/2007',
101+
'Time':'9:36am', 'Change':-0.46, 'Volume': 935000},
102+
]
103+
104+
with open('stocks.csv','w') as f:
105+
f_csv = csv.DictWriter(f, headers)
106+
f_csv.writeheader()
107+
f_csv.writerows(rows)
108+
109+
|
14110
15111
----------
16112
讨论
17113
----------
18-
todo...
114+
你应该总是优先选择csv模块分割或解析CSV数据。例如,你可能会像编写类似下面这样的代码:
115+
116+
.. code-block:: python
117+
118+
with open('stocks.csv') as f:
119+
for line in f:
120+
row = line.split(',')
121+
# process row
122+
...
123+
124+
使用这种方式的一个缺点就是你仍然需要去处理一些棘手的细节问题。
125+
比如,如果某些字段值被引号包围,你不得不去除这些引号。
126+
另外,如果一个被引号包围的字段碰巧含有一个逗号,那么程序就会因为产生一个错误大小的行而出错。
127+
128+
默认情况下,``csv`` 库可识别Microsoft Excel所使用的CSV编码规则。
129+
这或许也是最常见的形式,并且也会给你带来最好的兼容性。
130+
然而,如果你查看csv的文档,就会发现有很多种方法将它应用到其他编码格式上(如修改分割字符等)。
131+
例如,如果你想读取以tab分割的数据,可以这样做:
132+
133+
.. code-block:: python
134+
135+
# Example of reading tab-separated values
136+
with open('stock.tsv') as f:
137+
f_tsv = csv.reader(f, delimiter='\t')
138+
for row in f_tsv:
139+
# Process row
140+
...
141+
142+
如果你正在读取CSV数据并将它们转换为命名元组,需要注意对列名进行合法性认证。
143+
例如,一个CSV格式文件有一个包含非法标识符的列头行,类似下面这样:
144+
145+
.. code-block:: python
146+
147+
Street Address,Num-Premises,Latitude,Longitude
148+
5412 N CLARK,10,41.980262,-87.668452
149+
150+
这样最终会导致在创建一个命名元组时产生一个 ``ValueError`` 异常而失败。
151+
为了解决这问题,你可能不得不先去修正列标题。
152+
例如,可以像下面这样在非法标识符上使用一个正则表达式替换:
153+
154+
.. code-block:: python
155+
156+
import re
157+
with open('stock.csv') as f:
158+
f_csv = csv.reader(f)
159+
headers = [ re.sub('[^a-zA-Z_]', '_', h) for h in next(f_csv) ]
160+
Row = namedtuple('Row', headers)
161+
for r in f_csv:
162+
row = Row(*r)
163+
# Process row
164+
...
165+
166+
还有重要的一点需要强调的是,csv产生的数据都是字符串类型的,它不会做任何其他类型的转换。
167+
如果你需要做这样的类型转换,你必须自己手动去实现。
168+
下面是一个在CSV数据上执行其他类型转换的例子:
169+
170+
.. code-block:: python
171+
172+
col_types = [str, float, str, str, float, int]
173+
with open('stocks.csv') as f:
174+
f_csv = csv.reader(f)
175+
headers = next(f_csv)
176+
for row in f_csv:
177+
# Apply conversions to the row items
178+
row = tuple(convert(value) for convert, value in zip(col_types, row))
179+
...
180+
181+
另外,下面是一个转换字典中特定字段的例子:
182+
183+
.. code-block:: python
184+
185+
print('Reading as dicts with type conversion')
186+
field_types = [ ('Price', float),
187+
('Change', float),
188+
('Volume', int) ]
189+
190+
with open('stocks.csv') as f:
191+
for row in csv.DictReader(f):
192+
row.update((key, conversion(row[key]))
193+
for key, conversion in field_types)
194+
print(row)
195+
196+
通常来讲,你可能并不想过多去考虑这些转换问题。
197+
在实际情况中,CSV文件都或多或少有些缺失的数据,被破坏的数据以及其它一些让转换失败的问题。
198+
因此,除非你的数据确实有保障是准确无误的,否则你必须考虑这些问题(你可能需要增加合适的错误处理机制)。
199+
200+
最后,如果你读取CSV数据的目的是做数据分析和统计的话,
201+
你可能需要看一看 ``Pandas`` 包。``Pandas`` 包含了一个非常方便的函数叫 ``pandas.read_csv()`` ,
202+
它可以加载CSV数据到一个 ``DataFrame`` 对象中去。
203+
然后利用这个对象你就可以生成各种形式的统计、过滤数据以及执行其他高级操作了。
204+
在6.13小节中会有这样一个例子。
205+
206+

‎source/chapters/p06_data_encoding_and_process.rst‎

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,9 @@
22
第六章:数据编码和处理
33
=============================
44

5-
Python provides a variety of useful built-in data structures, such as lists, sets, and dictionaries.
6-
For the most part, the use of these structures is straightforward. However,
7-
common questions concerning searching, sorting, ordering, and filtering often arise.
8-
Thus, the goal of this chapter is to discuss common data structures and algorithms
9-
involving data. In addition, treatment is given to the various data structures contained
10-
in the collections module.
5+
这一章主要讨论使用Python处理各种不同方式编码的数据,比如CSV文件,JSON,XML和二进制包装记录。
6+
和数据结构那一章不同的是,这章不会讨论特殊的算法问题,而是关注于怎样获取和存储这些格式的数据。
7+
118

129
Contents:
1310

0 commit comments

Comments
 (0)