[TOC] 1.怎麼存數據 變數: age =10 字元串: name = "python" 列表: [1,2,3,"python"] 元組: (1,2,3)(不可以更改) 字典: {"a":100, "b":"666"} 2.怎麼用數據 數字操作符: +、 、 、/、%、//、\ \ 判斷迴圈: ...
目錄
1.怎麼存數據
- 變數: age =10
- 字元串: name = "python"
- 列表: [1,2,3,"python"]
- 元組: (1,2,3)(不可以更改)
- 字典: {"a":100, "b":"666"}
2.怎麼用數據
- 數字操作符: +、-、*、/、%、//、**
- 判斷迴圈:
- if判斷:
if a>10: b = a + 20 if b>20: pass elif: a>8: pass else: pass
- while迴圈
- if判斷:
while i<5:
# do something
pass
i = i + 1
while true:
pass
3.函數
# 位置參數
def person(name, age):
print(name,age)
# 預設參數
def person(name,age=20):
print(name, age)
# 關鍵字參數
def person(name, age, **kw):
print('name:', name, 'age:', age, 'other:', kw)
person('hao', 20) # name: Michael age: 30 other: {}
person('hao', 20, gener = 'M', job = 'Engineer') # name: Adam age: 45 other: {'gender': 'M', 'job': 'Engineer'}
extra = {'city': 'Beijing', 'job': 'Engineer'}
person('Jack', 24, **extra)
# 命名關鍵字參數
def person(name, age, *, city='Beijing', job):
print(name, age, city, job)
person('Jack', 24, job = '123')
person('Jack', 24, city = 'Beijing', job = 'Engineer')
# Combination
# 可變 + 關鍵字參數
def f1(a, b, c=0, *args, **kw):
print('a =', a, 'b =', b, 'c =', c, 'args =', args, 'kw =', kw)
f1(1, 2, 3, 'a', 'b') # a = 1 b = 2 c = 3 args = ('a', 'b') kw = {'x': 99}
f1(1, 2, 3, 'a', 'b', x=99) # a = 1 b = 2 c = 0 d = 99 kw = {'ext': None}
# 預設參數 + 命名關鍵字參數 + 關鍵字參數
def f2(a, b, c=0, *, d, **kw):
print('a =', a, 'b =', b, 'c =', c, 'd =', d, 'kw =', kw)
f2(1, 2, d=99, ext=None) # a = 1 b = 2 c = 0 d = 99 kw = {'ext': None}
4. 類和對象
4.1. 定義類的模板
class Student(object):
def __init__(self, name, score):
self.__name = name
self.__score = score
# print(mike)
def __str__(self):
msg = "name: " + self.__name + "score: " + str(self.__score)
return msg
# mike
__repr__ = __str__
# mike()
__call__ = __str__
@property
def name(self):
return self.__name
@name.setter
def name(self, value):
if type(value) == str:
self.__name = value
else:
raise ValueError('Bad name')
@property
def score(self):
return self.__score
@score.setter
def score(self, value):
if 0 <= value <= 100:
self.__score = value
else:
raise ValueError('Bad score')
def final_report(self):
if self.__score >= 90:
level = 'A'
elif self.__score >= 70:
level = 'B'
elif self.__score >= 60:
level = 'C'
else:
level = 'D'
msg = "Your final value is: " + level
return msg
# 調用
mike = Student('mike', 85)
print("-" * 20 + "Print property" + "-" * 20)
print(mike)
print("name: %s" % (mike.name))
print("-" * 30 + "Print methods" + "-" * 20)
print(mike.final_report())
print("-" * 30 + "Print modified infor" + "-" * 20)
mike.name = "Obama"
mike.score = 50
print("-" * 30)
print("modified name: %s" % (mike.name))
--------------------Print property--------------------
name: mikescore: 85
name: mike
------------------------------Print methods--------------------
Your final value is: B
------------------------------Print modified infor--------------------
------------------------------
modified name: Obama
4.2.繼承
class SixGrade(Student):
def __init__(self, name, score, grade):
super().__init__(name, score)
self.__grade = grade
# grade是一個只讀屬性
@property
def grade(self):
return self.__grade
def final_report(self, comments):
# 子類中調用父類方法
text_from_Father = super().final_report()
print(text_from_Father)
msg = "commants from teacher: " + comments
print(msg)
print("-" * 20 + "繼承" + "-" * 20)
fangfang = SixGrade('fang', 95, 6)
fangfang.final_report("You are handsome")
print(fangfang.grade)
--------------------繼承--------------------
Your final value is: A
commants from teacher: You are handsome
6
4.3 多態
class SixGrade(Student):
pass
class FiveGrade(Student):
pass
def print_level(Student):
msg = Student.final_report()
print(msg)
print_level(Student('from class', 90))
print_level(SixGrade('from subclass-1', 56))
print_level(FiveGrade('from subclass-2', 85))
Your final value is: A
Your final value is: D
Your final value is: B
5. IO文件操作和OS目錄操作
OS操作
import os
# 獲取當前目錄的絕對路徑
path = os.path.abspath('.')
# 創建一個目錄
os.path.join('/Users/michael', 'testdir')
os.mkdir('/Users/michael/testdir')
# 刪除一個目錄
os.rmdir('/Users/michael/testdir')
# 拆分路徑
os.path.split('/Users/michael/testdir/file.txt') # ('/Users/michael/testdir', 'file.txt')
os.path.splitext('/path/to/file.txt') # ('/path/to/file', '.txt')
# 重命名
os.rename('test.txt', 'test.py')
# 刪除文件
os.remove('test.py')
# 列出所有python文件
[x for x in os.listdir('.') if os.path.isfile(x) and os.path.splitext(x)[1]=='.py']
IO文件
方法 | 特性 | 性能 |
---|---|---|
read() |
讀取全部內容 | 一般 |
readline() |
每次讀出一行內容 | 占用記憶體最少 |
readlines() |
讀取整個文件所有行,保存在一個列表(list)變數中,每行作為一個元素 | 最好(記憶體足) |
write() |
寫文件 |
# 讀
# 下麵是read()方法的使用,“r”表示read
with open('testRead.txt', 'r', encoding='UTF-8') as f1:
results = f1.read() # 讀取數據
print(results)
# 下麵是readline()方法的使用,“r”表示read
with open('testRead.txt', 'r', encoding='UTF-8') as f2:
line = f2.readline() # 讀取第一行
while line is not None and line != '':
print(line)
line = f2.readline() # 讀取下一行
# 下麵是readlines()方法的使用,“r”表示read
with open('testRead.txt', 'r', encoding='UTF-8') as f3:
lines = f3.readlines() # 接收數據
for line in lines: # 遍曆數據
print(line)
# 寫
with open('/User/test.txt', 'w') as f:
f.write('hello')
6. 正則表達式及re模塊的使用
主要參考資料為:
-
6.1. 正則表達式語法
6.2. re模塊的使用
內置的 re 模塊來使用正則表達式,提供了很多內置函數:
- pattern = re.compile(pattern[, flag]):
- 參數:
- pattern: 字元串形式的正則
- flag: 可選模式,表示匹配模式
- pattern: 字元串形式的正則
- 例子:
import re
pattern = re.compile(r'\d+')
- Pattern的常用方法
import re
pattern = re.compile(r'\d+')
m0 = pattern.match('one12twothree34four')
m = pattern.match('one12twothree34four', 3, 10)
print("-" * 15 + "Match methods" + "-" * 15)
print("found strings: ", m.group(0))
print("start index of found strings: ", m.start(0))
print("end index of found strings: ", m.end(0))
print("Span length of found strigns: ", m.span(0))
s = pattern.search('one12twothree34four')
print("-" * 15 + "Search methods" + "-" * 15)
print("found strings: ", s.group(0))
print("start index of found strings: ", s.start(0))
print("end index of found strings: ", s.end(0))
print("Span length of found strigns: ", s.span(0))
f = pattern.findall('one1two2three3four4', 0, 10)
print("-" * 15 + "findall methods" + "-" * 15)
print("found strings: ", f)
f_i = pattern.finditer('one1two2three3four4', 0, 10)
print("-" * 15 + "finditer methods" + "-" * 15)
print("type of method: ", type(f_i))
for m1 in f_i: # m1 是 Match 對象
print('matching string: {}, position: {}'.format(m1.group(), m1.span()))
p = re.compile(r'[\s\,\;]+')
print("-" * 15 + "Split methods" + "-" * 15)
print("split a,b;c.d: ", p.split('a,b;; c d'))
p1 = re.compile(r'(\w+) (\w+)')
s1 = 'hello 123, hello 456'
def func(m):
return 'hi' + ' ' + m.group(2)
print("-" * 15 + "替換 methods" + "-" * 15)
print(p1.sub(r'hello world', s1)) # 使用 'hello world' 替換 'hello 123' 和 'hello 456'
print(p1.sub(r'\2 \1', s1)) # 引用分組
print(p1.sub(func, s1))
print(p1.sub(func, s1, 1)) # 最多替換一次
結果是:
---------------Match methods---------------
found strings: 12
start index of found strings: 3
end index of found strings: 5
Span length of found strigns: (3, 5)
---------------Search methods---------------
found strings: 12
start index of found strings: 3
end index of found strings: 5
Span length of found strigns: (3, 5)
---------------findall methods---------------
found strings: ['1', '2']
---------------finditer methods---------------
type of method: <class 'callable_iterator'>
matching string: 1, position: (3, 4)
matching string: 2, position: (7, 8)
---------------Split methods---------------
split a,b;c.d: ['a', 'b', 'c', 'd']
---------------替換 methods---------------
hello world, hello world
123 hello, 456 hello
hi 123, hi 456
hi 123, hello 456