Lean Python(Chapter 11)

Sun 24 September 2017 by Little Captain

Databases

SQLite

数据库函数

# 打开连接数据库
conn = sqlite3.connect(filename)
# 执行 SQL
conn.executescript(sql)
# 返回游标
cursor = conn.cursor()
# 执行查询操作, 返回数据
cursor.execute(sql)
rows = cursor.fetchall()

连接和导入数据 (SQLite)

# insert
import os
import sqlite3

db_filename='mydatabase.db'

exists = os.path.exists(db_filename)
if exists:
    os.unlink(db_filename)

conn = sqlite3.connect(db_filename)

schema="""create table person (
  id integer primary key autoincrement not null,
  name text not null,
  dob date,
  nationality text,
  gender text)
"""
conn.executescript(schema)

people="""insert into person (name, dob, nationality, gender)
values ('Fred Bloggs', '1965-12-25','British','Male');
insert into person (name, dob,nationality,gender)
values ('Santa Claus', '968-01-01','Lap','Male');
insert into person (name, dob,nationality,gender)
values ('Tooth Fairy', '1931-03-31','American','Female');
"""
conn.executescript(people)

cursor = conn.cursor()
cursor.execute("select id, name, dob, nationality, gender from person")
for row in cursor.fetchall():
    id, name, dob, nationality, gender = row
    print("%3d %15s %12s %10s %6s" % (id, name, dob, nationality, gender))

# 省略了 name 字段, 使其抛出一个异常
try:
    dupe="insert into person (id, dob,nationality,gender) \
    values (1,'1931-03-31','American','Female');"
    conn.executescript(dupe)
except Exception as e:
    print('Cannot insert record',e.__class__.__name__)
# update
import sqlite3
import sys

db_filename = 'mydatabase.db'
inid = sys.argv[1]
innat = sys.argv[2]

conn = sqlite3.connect(db_filename)
cursor = conn.cursor()

query = "update person set nationality = :nat where id = :id"
cursor.execute(query, {'id':inid, 'nat':innat})

cursor.execute("select id, name, dob,nationality,gender from person")
for row in cursor.fetchall():
    id, name, dob, nationality, gender = row
    print("%3d %15s %12s %10s %6s" % (id, name, dob, nationality, gender))

Lean Python(Chapter 10)

Sat 23 September 2017 by Little Captain

字符串搜索

  • find 返回字符串出现的字符位置, 如果没有找到就返回 -1
txt="The quick brown fox jumps over the lazy dog"
txt.find('jump')
txt.find('z')
txt.find('green')

正则表达式

# 匹配邮箱
import re

regex = '\s[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}[\s]'
text = """This is some text with x@y.z embedded e-mails
that we …
read more

Lean Python(Chapter 09)

Sat 23 September 2017 by Little Captain

Accessing the Web

import requests
from urllib.parse import urlparse

url = input('Web url to fetch:')
urlparts = urlparse(url)
if urlparts[0] == '':
    url = ''.join(('http://', url))

qstring = input('Enter query string:')
if len(qstring) > 0:
    url = '?'.join((url, qstring))

save = input('Save downloaded page to disk [y/n]?')

print('Requesting …
read more

Lean Python(Chapter 08)

Sat 23 September 2017 by Little Captain

Testing Your Code

模块化编程与代码测试

  • 模块化编程是测试更为容易

测试驱动的开发(TDD)

  1. 开发代码前先写测试
  2. 运行测试, 观察失败, 然后添加和修正代码, 使测试通过
  3. 当测试通过后, 寻求改进代码设计的机会
  • 对于大型项目, TDD 能够最好的模块化你的代码

单元测试框架 : unittest

def calc(a, op, b):
    if op not in '+-/*':
        return None, 'Operator must be +-/*'
    try:
        if op == '+':
            result = a + b
        elif op == '-':
            result = a - b
        elif op == '/':
            result = a / b
        else …
read more

Lean Python(Chapter 07)

Sat 23 September 2017 by Little Captain

Exception and Error Handling

异常和错误的处理

print('Input two numbers. the first will be divided by the second')

afirst = input('first number:')
first=float(afirst)
asecond = input('second number:')
second = float(asecond)

quotient = first / second
print('Quotient first/second = ',quotient)
print('Input two numbers. the first will be divided by the …
read more

Lean Python(Chapter 06)

Sat 23 September 2017 by Little Captain

Object Orientation

创建对象

类的定义

  • 类是对象的模板
from datetime import datetime

class person(object):
    "Person Class"
    def __init__(self, name, age, parent = None):
        self.name =name
        self.age = age
        self.created = datetime.today()
        self.parent = parent
        self.children = []
        print('Created', self.name, 'age', self.age)

    def setName(self, name):
        self.name = name …
read more

Lean Python(Chapter 05)

Fri 22 September 2017 by Little Captain

Module

导入模块

  • 一个文件就是一个模块, 模块名就是文件名
# as 使用自定义的名字引用这个模块
import modulename [as name]
# 从模块中引入指定的函数、类、变量等
from module import function1, function2...
# 从模块中引入所有的内容, 这时直接使用, 而不需要使用 . 引用
from module import *
  • 注意 : 通常, 导入模块的需要内容和功能, 而要避免使用 import *

Python 自带模块

  • 查看 Python 环境 Path
import sys
sys.path
read more

Lean Python(Chapter 04)

Thu 21 September 2017 by Little Captain

Input and Output

显示输出

# 格式
print(arg1,arg2,arg3...,sep=' ',end='\n')
  • 使用格式输出
print('%d plus %d makes %d' % (3, 7, 10))
  • 抑制最后的空行输出
print('one...','two...','three',end='')

获取用户输入

yourName=input('Enter your name: ')
  • 接收的输入都是字符串, 所以要用户输入数字等需要自行解析
count = input('Enter a number: ')
if len(count) > 0:
    if count.isdigit():
        count = int …
read more

Lean Python(Chapter 03)

Thu 21 September 2017 by Little Captain

Program Structure

做决定

if 语句

if test:
    statement1 # 如果条件为真, 这三条语句都将执行
    statement2
    statement3
# if else
if test:
    DoThis()
else:
    DoThat()
# if elif else
if test1:
    DoThis()
elif test2:
    DoThat()
else:
    DoOther()
  • 同一语句中的 if elif else 的缩进必须保持一致

pass 语句

  • pass 语句就是什么都不做
if test1:
    DoThis()
elif test2:
    DoThat()
# else 不是严格必须, 但是加上, 通过使用 pass …
read more

Lean Python(Chapter 02)

Tue 19 September 2017 by Little Captain

Everything is Object

对象类型

# 使用 type 查看对象类型
type(23)

类型有 : int str list class function file bool(True、False) NoneType(None) long

工厂方法

int(4.0)
str(4)
list(1, 2, 3, 4)
tuple(1, 2, 3, 4)
dict(one = 1, two = 2)

12345678901234567890
1 / 7.0
x = 1E20 …
read more