Professional Documents
Culture Documents
Python Training Course VII: String and File Processing
Python Training Course VII: String and File Processing
Format
Match with Regular Expressions
File Input/Output
Structured Text Files
CSV
XML
JSON
2
Format : Old style with %
3
Format : Old style with %
4
New style formatting with {} and format
引數也可以是名字
{0} 是 d, {1}
是’ other’
5
New style formatting with {} and format
引數可以是數字可以是名稱
精度不適用整數
: 之後是填充字元
7
Match with Regular Expressions ( 正規表示式 )
8
Match with Regular Expressions ( 正規表示式 )
match() works only if the pattern search() works if the pattern is anywhere
is at the beginning of the source
9
Match with Regular Expressions ( 正規表示式 )
10
First match with search(), All matches with findall()
? Zero or one
11
Split at matches with split()
12
Patterns: special characters
13
Patterns: special characters
which contains 100 printable ASCII characters
digits
alphanumeric character :
digits, letters, or an underscore
whitespaces
14
Pattern specifiers
15
Pattern specifiers
wish or fish
開頭是 I wish
結尾是 fish
16
Pattern specifiers
w or f
17
Using Python’s raw strings
18
Patterns: specifying match output
19
A Regular Expression example in the real world
(r’\r\n’
)
Book P.170
Things to Do 7.7~7.11
21
File Input/Output
22
Write a Text File with write()
最後要記得 close
23
print() or write()
By default, print() adds a space after each
argument and a newline at the end.
24
Write file from a large source string
25
Write to an existed file
26
Read a Text File with read()
read 100 characters at a
time and append each
chunk to a poem string
read() 也要
close
27
Read a Text File with readline()
Pythonic
28
Read a Text File with readlines()
把 newline 拿
掉
29
Close Files Automatically by Using with
自動關檔
30
練習題
Book P.215
Things to Do 8.1~8.2
31
CSV File
Write CSV file
villains file
32
csv.DictReader() villains file
33
csv.DictWriter()
34
villains file
CSV 檔有表頭就
不必用
fieldnames
35
練習題
Book P.215
Things to Do 8.3~8.5
36
XML File into dict.
menu.xml
into
dict.
37
Other XML library
JSON File
menu
into string
39