1. 程式人生 > >python 對模塊的應用你還得練點這些

python 對模塊的應用你還得練點這些

datetime att 請問 access update 價格 timeout div ket

1.有如下字符串:n = "路飛學城"(編程題)

  • - 將字符串轉換成utf-8的字符編碼的字節,再將轉換的字節重新轉換為utf-8的字符編碼的字符串
  • - 將字符串轉換成gbk的字符編碼的字節,再將轉換的字節重新轉換為utf-8的字符編碼的字符串
n = ‘路飛學誠‘

print(n.encode(‘utf-8‘))
# b‘\xe8\xb7\xaf\xe9\xa3\x9e\xe5\xad\xa6\xe8\xaf\x9a‘
print(n.encode(‘utf-8‘).decode(‘utf-8‘))
# 路飛學誠
print(n.encode(‘gbk‘))
# b‘\xc2\xb7\xb7\xc9\xd1\xa7\xb3\xcf‘
print(n.encode(‘gbk‘).decode(‘gbk‘))
# 路飛學誠
print(n.encode(‘gbk‘).decode(‘gbk‘).encode(‘utf-8‘))
# b‘\xe8\xb7\xaf\xe9\xa3\x9e\xe5\xad\xa6\xe8\xaf\x9a‘
print(n.encode(‘gbk‘).decode(‘gbk‘).encode(‘utf-8‘).decode(‘utf-8‘))
# 路飛學誠

2,讀文件找到第9個字符,華 ,找到第二行的 實,刪除最後一行 寫入文件

桃之夭夭,灼灼其華。之子於歸,宜其室家。
桃之夭夭,有蕡其實。之子於歸,宜其家室。
桃之夭夭,其葉蓁蓁。之子於歸,宜其家人。

  

f = open(‘poem.txt‘, ‘r+‘, encoding=‘utf-8‘)

f.seek(3*8)
print(f.read(1))

f.seek(3*28+2)
print(f.read(1))

data_list = f.readlines()
print(data_list)
data_list.pop()
print(data_list)
f.seek(0)
f.truncate()
f.write(‘‘.join(data_list))

  

3,求出函數的執行時間,利用裝飾器

import time
def time_func(func):
    def wrapper(*args,**kwargs):
        time_start = time.time()
        func(*args,**kwargs)
        time_end = time.time()
        print(time_end-time_start)
    return wrapper
@time_func
def x(a,b):
    time.sleep(1)
    return a+b

x(1,8)
# 結果:1.0001220703125

  

帶參數的裝飾器

# 帶參數的裝飾器
import time
def show_timw(func):

    def wrapper(a,b):
        start_time = time.time()
        ret = func(a,b)
        end_time = time.time()
        print("消耗時間為:%s" %(end_time-start_time))
        return ret

    return wrapper

@show_timw
def add(a,b):
    time.sleep(1)
    return a+b

print(add(48,45))
# 結果:
# 消耗時間為:1.0008337497711182
# 93

4.作用域

def test():
    print(luffy)

luffy = "the king of sea."
test()

# 結果:the king of sea.

  

5,li = [1,2,3,5,5,6,7,8,9,9,8,3] 利用生成器功能,寫一個所有數值乘以2的功能

li = [1,2,3,5,5,6,7,8,9,9,8,3]
res = (i*2 for i in li)

# print(list(res))
# 結果:[2, 4, 6, 10, 10, 12, 14, 16, 18, 18, 16, 6]

# print(next(res))
# 結果:2(一次取一個值)

for i in res:
    print(i)
# 結果:2
# 4
# 6
# 10
# 10
# 12
# 14
# 16
# 18
# 18
# 16
# 6

print(res.__next__())
# 結果:2

  

6.打印日誌11/26/2017 10:44:21 PM bug 24 並寫入文件example.log中

import logging
logging.basicConfig(filename=‘example.log‘, format=‘%(asctime)s - %(message)s‘, datefmt=‘%m/%d/%Y %I:%M:%S %p‘, level=logging.DEBUG)
logging.warning(‘bug 24‘)

# 文件內容:
# 03/24/2018 08:52:36 PM - bug 24

  

7,json和pickle

import json,pickle  # json 可序列化的有 int str list tuple dict 沒有集合
# pickle 可序列化python所有數據類型包括函數 pickle 可序列化一些類 但類需要引用
li = [1,2,3]
dict = {1,2,3}
def fun():
    return 3
str_data = json.dumps(li)
print(type(str_data),str_data)
# 結果:<class ‘str‘> [1, 2, 3]

list_data = json.loads(str_data)
print(list_data,type(list_data))
# 結果:[1, 2, 3] <class ‘list‘>

s = pickle.dumps(li)
print(s,type(s))
# 結果:b‘\x80\x03]q\x00(K\x01K\x02K\x03e.‘ <class ‘bytes‘>

data = pickle.loads(s)
print(data,type(data))
# 結果:[1, 2, 3] <class ‘list‘>

with open(‘test.txt‘,‘w‘,encoding=‘utf-8‘) as f:
    json.dump(li,f)

data = json.load(open(‘test.txt‘,‘r‘,encoding=‘utf-8‘))
print(data,type(data))
# 結果:[1, 2, 3] <class ‘list‘>

pickle.dump(li,open(‘test1.txt‘,‘wb‘))
data = pickle.load(open(‘test1.txt‘,‘rb‘))
print(data,type(data))
# 結果:[1, 2, 3] <class ‘list‘>

pickle.dump(fun,open(‘test2.txt‘,‘wb‘))
data = pickle.load(open(‘test2.txt‘,‘rb‘))
print(data())
# 結果:3

  

8,閉包

def fun1():
    n = 10
    def fun2():
        return n
    return fun2
f=fun1()
print(f())
# 結果:10

  

9,生成器 叠代器

# 生成器:
s = (i for i in range(10))
print(next(s))
# 結果:0

# 叠代器:
def fun(n):
    x=0
    while(x<n):
        yield x
        x+=1
s = fun(3)
print(next(s))
print(s.__next__())
# 結果:0
# 1

from collections import Iterable,Iterator
print(isinstance({1,2,3},Iterable))
# 結果:True

s = iter([1,2,3,4,3,2,1])
print(s.__next__())
# 結果:
# 1
# 2
# 3
# 4
print(next(s))
# 結果:
# 1
# 2
# 3
# 4
for i in s:
    print(i)
# 結果:
# 1
# 2
# 3
# 4
# 3
# 2
# 1

  

10,斐波那契數列

def fun(x):
    n, a, b = 0, 0, 1
    while n < x:
        yield b
        a, b = b, a + b
        n += 1

  結果:

res = fun(4)
# for i in res:
#     print(i)
# 結果:1
# 1
# 2
# 3

print(next(res))
print(next(res))
print(next(res))
print(next(res))
print(next(res))
# 結果:1
# 1
# 2
# 3
# StopIteration

  

11,map filter globals() locals() hash()

print(globals())
# {‘__name__‘: ‘__main__‘, ‘__doc__‘: None, ‘__package__‘: None, ‘__loader__‘:
# <_frozen_importlib_external.SourceFileLoader object at 0x0000017306D6B080>, ‘__spec__‘:
# None, ‘__annotations__‘: {}, ‘__builtins__‘: <module ‘builtins‘ (built-in)>,
#                                                      ‘__file__‘:
# ‘D:/exer.py‘, ‘__cached__‘: None}
print(locals())
# {‘__name__‘: ‘__main__‘, ‘__doc__‘: None, ‘__package__‘: None, ‘__loader__‘:
# <_frozen_importlib_external.SourceFileLoader object at 0x0000017306D6B080>, ‘__spec__‘:
# None, ‘__annotations__‘: {}, ‘__builtins__‘: <module ‘builtins‘ (built-in)>,
# ‘__file__‘: ‘D:/exer.py‘, ‘__cached__‘: None}
n1=[1,2,3]
def fun():
    n1[1] =‘123‘
    return n1
print(fun())
# 結果:[1, ‘123‘, 3]

print(‘n1是什麽: ‘,n1)
# 結果:n1是什麽:  [1, ‘123‘, 3]

  

res = map(lambda x:x*2,[1,2,3])
for i in res:
    print(i)
# 結果:
# 2
# 4
# 6
print(list(res))
# 結果:[2, 4, 6]

  

res = filter(lambda x:x%2==0,list(range(10)))
# for i in res:
#     print(i)
# 結果:
# 0
# 2
# 4
# 6
# 8

print(res.__next__())
# 結果: 0

print(next(res))
# 結果: 0

print(hash((1,2,3))) # 只有 不可變的才可哈希 int str tuple 如:list dict set 不能被哈希
# 結果:2528502973977326415

  

12,三目 匿名 lambda

a = 2
b = 5
print(a if a>b else b)
# 結果:5

res =lambda a,b: a if a>b else b
print(res(2,3))
# 結果:3

fun = lambda x,y:x+y
print(fun(2,3))
# 結果:5

fun = lambda x,y:x if x>y else y
print(fun(2,3))
# 結果:3

res = map(lambda x:x*x,list(range(5)))
for i in res:
    print(i)
# 結果:
# 0
# 1
# 4
# 9
# 16

fun = lambda x,y:x/y if x>y else x*y
print(fun(4,3))
# 結果:1.3333333333333333

  

13,time datetime

import time 
import datetime
print(time.time())
# 結果:1521903163.3908226
print(time.asctime())
# 結果:Sat Mar 24 22:52:43 2018
print(time.gmtime())
# 結果:time.struct_time(tm_year=2018, tm_mon=3, tm_mday=24, tm_hour=14, tm_min=52, tm_sec=43, tm_wday=5, tm_yday=83, tm_isdst=0)
print(time.strftime(‘%Y-%m-%d %I:%M:%S %p‘,time.localtime()))
# 結果: 2018-03-24 10:52:43 PM
str_time =time.strftime(‘%Y-%m-%d %I:%M:%S %p‘,time.localtime())
# print(str_time)
# 結果:2018-03-24 10:52:43 PM
res = time.strptime(str_time,‘%Y-%m-%d %I:%M:%S %p‘)
print(res)
# 結果:time.struct_time(tm_year=2018, tm_mon=3, tm_mday=24, tm_hour=22, tm_min=55, tm_sec=10, tm_wday=5, tm_yday=83, tm_isdst=-1)
print(time.mktime(res))
# 結果:1521903326.0
res =datetime.datetime.now() + datetime.timedelta(days=2,hours=3)
print(res)
# 結果:2018-03-27 01:55:43.520904
res1 = datetime.datetime.now().replace(year=2015,month=2,day=2)
print(res1)
# 結果:2015-02-02 22:55:58.174786
print(datetime.date.fromtimestamp(time.time()))
# 結果:2018-03-24
print(random.randint(1,3)) # 會包含3
print(random.randrange(1,3)) # 不會包含3
print(random.random())
print(random.choice(‘123123‘))

  

14,random模塊

import random
print(random.randint(1,3)) # 會包含3
print(random.randrange(1,3)) # 不會包含3
print(random.random())
print(random.choice(‘123123‘))
# 結果:
# 3
# 1
# 0.8458542042848031
# 1

  

import string
# digits:獲取所有的10進制數字字符
# punctuation:獲取所有的標點符號
# ascii_letters:獲取所有ascii碼中字母字符的字符串(包含大寫和小寫)
print(‘‘.join(random.sample(string.digits+string.punctuation+string.ascii_letters,6)))
# 結果:.uim4D

li = list(range(10))
random.shuffle(li)
print(li)
# 結果: [5, 2, 1, 7, 6, 3, 4, 8, 0, 9]

  

15,os模塊

得到當前工作目錄,即當前Python腳本工作的目錄路徑: os.getcwd()
返回指定目錄下的所有文件和目錄名:os.listdir()
函數用來刪除一個文件:os.remove()
刪除多個目錄:os.removedirs(r“c:\python”)
檢驗給出的路徑是否是一個文件:os.path.isfile()
檢驗給出的路徑是否是一個目錄:os.path.isdir()
判斷是否是絕對路徑:os.path.isabs()
檢驗給出的路徑是否真地存:os.path.exists()
返回一個路徑的目錄名和文件名:os.path.split()     e.g os.path.split(‘/home/swaroop/byte/code/poem.txt‘) 結果:(‘/home/swaroop/byte/code‘, ‘poem.txt‘) 
分離擴展名:os.path.splitext()       e.g  os.path.splitext(‘/usr/local/test.py‘)    結果:(‘/usr/local/test‘, ‘.py‘)
獲取路徑名:os.path.dirname()
獲得絕對路徑: os.path.abspath()  
獲取文件名:os.path.basename()
運行shell命令: os.system()
讀取操作系統環境變量HOME的值:os.getenv("HOME") 
返回操作系統所有的環境變量: os.environ 
設置系統環境變量,僅程序運行時有效:os.environ.setdefault(‘HOME‘,‘/home/alex‘)
給出當前平臺使用的行終止符:os.linesep    Windows使用‘\r\n‘,Linux and MAC使用‘\n‘
指示你正在使用的平臺:os.name       對於Windows,它是‘nt‘,而對於Linux/Unix用戶,它是‘posix‘
重命名:os.rename(old, new)
創建多級目錄:os.makedirs(r“c:\python\test”)
創建單個目錄:os.mkdir(“test”)
獲取文件屬性:os.stat(file)
修改文件權限與時間戳:os.chmod(file)
獲取文件大小:os.path.getsize(filename)
結合目錄名與文件名:os.path.join(dir,filename)
改變工作目錄到dirname: os.chdir(dirname)
獲取當前終端的大小: os.get_terminal_size()
殺死進程: os.kill(10884,signal.SIGKILL)

  

16,sys模塊

sys.argv           命令行參數List,第一個元素是程序本身路徑
sys.exit(n)        退出程序,正常退出時exit(0)
sys.version        獲取Python解釋程序的版本信息
sys.maxint         最大的Int值
sys.path           返回模塊的搜索路徑,初始化時使用PYTHONPATH環境變量的值
sys.platform       返回操作系統平臺名稱
sys.stdout.write(‘please:‘)  #標準輸出 , 引出進度條的例子, 註,在py3上不行,可以用print代替
val = sys.stdin.readline()[:-1] #標準輸入
sys.getrecursionlimit() #獲取最大遞歸層數
sys.setrecursionlimit(1200) #設置最大遞歸層數
sys.getdefaultencoding()  #獲取解釋器默認編碼
sys.getfilesystemencoding  #獲取內存數據存到文件裏的默認編碼

  

17,作用域,範圍

x = 10
def add(a, b=x):
    return a + b

ret = add(10)
print(ret)  # 輸出 20

x = 20
ret = add(10)
print(ret)  # 輸出 20 不是30 註意模塊執行的流程 從上到下

  

18,lambda的應用

# 2.lambda 的應用
# ---CASE 1
fs = map(lambda i:(lambda j: i*j), range(6))
print([f(2) for f in fs])

#---CASE 2
fs = [lambda j:i*j for i in range(6)]
print([f(2) for f in fs])

#---CASE 3
fs = []
for i in range(6):
    fs.append(lambda j:i*j)
    if i==3:
        break
print([f(2) for f in fs])

#---CASE 4
fs = [(lambda i:lambda j:i*j)(i) for i in range(6)]
print([f(2) for f in fs])

# 結果:
# [0, 2, 4, 6, 8, 10]
# [10, 10, 10, 10, 10, 10]
# [6, 6, 6, 6]
# [0, 2, 4, 6, 8, 10]

19,logging模塊有幾個日誌級別?

    總共有5個級別,默認級別是WARNING,
    按照級別高低分別為CRITICAL    ERROR    WARNING  INFO DEBUG

  

20,請配置logging模塊,使其在屏幕和文件裏同時打印以下格式的日誌

2017-10-18 15:56:26,613 - access - ERROR - account [1234] too many login attempts

  

# 20,請配置logging模塊,使其在屏幕和文件裏同時打印以下格式的日誌
# 2017-10-18 15:56:26,613 - access - ERROR - account [1234] too many login attempts
import logging

logger = logging.getLogger(‘mylog‘)
logger.level = logging.INFO

# 創建一個handler,用於寫入日誌文件
fh = logging.FileHandler(‘exer.log‘)
# 再創建一個handler,用於寫入輸出控制臺
ch = logging.StreamHandler()
fh.level = logging.WARNING
ch.level = logging.ERROR

logger.addHandler(fh)
logger.addHandler(ch)

formatter = logging.Formatter(‘%(asctime)s - %(name)s - %(levelname)s - %(lineno)s %(message)s‘)


fh.setFormatter(formatter)
ch.setFormatter(formatter)



logger.debug(‘too many login attempts‘)
logger.info(‘too many login attempts‘)
logger.warning(‘too many login attempts‘)
logger.error(‘too many login attempts‘)
logger.critical(‘too many login attempts‘)

  

21,json,pickle,shelve三個區別是什麽?

    json:轉化的數據類型,int str list tuple dict 不支持set
    json只可以用於字符串或者字典等與python數據類型之間的序列化與反序列化之間的操作

    pickle:支持python裏面所有的數據類型,只能在python裏使用,函數也可以序列化
    pickle可以用於python類有類型與python數據類型之間的序列化與反序列化的操作

    shelve:pickle封裝了shelve,只能在python裏使用,也就是說shelve對pickle進行了包裝,是一個鍵值對的形式,shelve模塊很簡單,只有一個open函數

  

22,json的作用是什麽?

    將內存的數據類型轉化為字符串,使其能存儲到硬盤上或者通過網絡傳輸到遠程,因為硬盤或者網絡傳輸只接受bytes類型。
    JSON不僅是標準格式,而且比XML更快,而且可以在web頁面直接讀取,非常方便。

  

23,subprocess執行命令方式有幾種?

三種執行命令的方法:

    subprocess.run(*popenargs, input=None, timeout=None, check=False, **kwargs) #官方推薦

    subprocess.call(*popenargs, timeout=None, **kwargs) #跟上面實現的內容差不多,另一種寫法

    subprocess.Popen() #上面各種方法的底層封裝

  

24,為什麽要設計好目錄結構?

    可讀性高: 不熟悉這個項目的代碼的人,一眼就能看懂目錄結構,知道程序啟動腳本是哪個
,測試目錄在哪兒,配置文件在哪兒等等。從而非常快速的了解這個項目。

    可維護性高: 定義好組織規則後,維護者就能很明確地知道,新增的哪個文件和代碼應該放
在什麽目錄之下。這個好處是,隨著時間的推移,代碼/配置的規模增加,項目結構不會混亂,
仍然能夠組織良好。

  

25,打印出命令行的第一個參數,例如:打印出 luffy

python argument.py luffy

  

26,代碼如下:

‘‘‘
Linux當前目錄/usr/local/nginx/html/
文件名:index.html
‘‘‘
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(index.html)))
print(BASE_DIR)

  

打印的內容是什麽? nginx
os.path.dirname和os.path.abspath含義是什麽?
目錄名,絕對路徑

27,通過configparser模塊完成以下功能

文件名my.ini

[DEFAULT]

[client]
port = 3306
socket = /data/mysql_3306/mysql.sock

[mysqld]
explicit_defaults_for_timestamp
port = 3306
socket = /data/mysql_3306/mysql.sock
back_log = 80
basedir = /usr/local/mysql
tmpdir = /tmp
datadir = /data/mysql_3306
default-time-zone = ‘+8:00‘

  

  1. 修改時區 default-time-zone = ‘+8:00‘ 為 校準的全球時間 +00:00
  2. 刪除 explicit_defaults_for_timestamp
  3. 為DEFAULT增加一條 character-set-server = utf8
# _*_ coding: utf-8 _*_ 


# 1.修改時區 default-time-zone = ‘+8:00‘ 為 校準的全球時間 +00:00
# 2.刪除 explicit_defaults_for_timestamp
# 3.為DEFAULT增加一條 character-set-server = utf8

import configparser


# 創建ConfigParser實例
config = configparser.ConfigParser()

# 讀取配置文件
res = config.read(‘my.ini‘)
print(res)
config.set(‘mysqld‘,‘default-time-zone ‘,‘+00.00‘)
config.write(open(‘my.ini‘,‘w‘))
# 設置sections節點中,鍵名為options的值
config.remove_option(‘mysqld‘,‘explicit_defaults_for_timestamp‘)
config.write(open(‘my.ini‘,‘w‘))
config.set(‘DEFAULT‘,‘character-set-server ‘,‘utf8‘)
config.write(open(‘my.ini‘,‘w‘))

  

28,寫一個6位隨機驗證碼程序(使用random模塊),要求驗證碼中至少包含一個數字、一個小寫字母、一個大寫字母.

# 10,寫一個6位隨機驗證碼程序(使用random模塊),
# 要求驗證碼中至少包含一個數字、一個小寫字母、一個大寫字母.

import random
import string

# ascii_letters:獲取所有ascii碼中字母字符的字符串(包含大寫和小寫)
# digits:獲取所有的10進制數字字符
res = ‘‘.join(random.sample(string.digits+string.ascii_letters,6))
# res = ‘‘.join(random.sample(string.ascii_lowercase + string.digits, 6))
print(res)

  

29,利用正則表達式提取到 luffycity.com ,內容如下

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <title>luffycity.com</title>
</head>
<body>
</body>
</html>

# 11,利用正則表達式提取到 luffycity.com ,內容如下
import re

with open(‘str.txt‘,‘r‘,encoding=‘utf-8‘) as f:
    data = f.read()
    print(data)
    res = re.search(‘\w+\.com‘,data).group()
    print("結果 ",res)

  

30,寫一個用戶登錄驗證程序,文件如下:1234.json

{"expire_date": "2021-01-01", "id": 1234, "status": 0, "pay_day": 22, "password": "abc"}

  

  1. 用戶名為json文件名,密碼為 password。
  2. 判斷是否過期,與expire_date進行對比。
  3. 登陸成功後,打印“登陸成功”,三次登陸失敗,status值改為1,並且鎖定賬號。

# 12,寫一個用戶登錄驗證程序,文件如下:1234.json
# {"expire_date": "2021-01-01", "id": 1234, "status": 0, "pay_day": 22, "password": "abc"}
#   
# 用戶名為json文件名,密碼為 password。
# 判斷是否過期,與expire_date進行對比。
# 登陸成功後,打印“登陸成功”,三次登陸失敗,status值改為1,並且鎖定賬號。
import os
import json
import time

def user_login():
    retry_count = 0
    while retry_count<3:
        account = input(‘\033[32;1mplease input Acount:\033[0m‘).strip()
        password = input(‘\033[32;1mplease input Password:\033[0m‘).strip()
        load_file(account)
        access_auth(account,password)
        retry_count += 1
    else:
        update_file(account)
def access_auth(account,password):
    account_data = load_file(account)
    if account_data[‘status‘] == 0:
        if account_data[‘password‘]  == password:
            expire_time = time.mktime(time.strptime(account_data[‘expire_date‘],‘%Y-%m-%d‘))
            if time.time() > expire_time:        #如果信用卡已經過期,當前時間戳大於國企的時間戳
                print("\033[31;1mAccount %s had expired,Please contract the bank"%account)
                exit()
            else:       #信用卡未過期,返回用戶數據的字典
                return account_data
        else:
            print("\033[31;1mAccount or Passwordoes not correct!\033[0m")
    else:
        print("\033[31;1mAccount already be lock\033[0m")
        exit()
def load_file(account):
    file_name = ‘%s.json‘%account
    if os.path.isfile(file_name):
        with open(file_name,‘r‘,encoding=‘utf-8‘) as f:
            acc_data = json.load(f)
            return acc_data
    else:
        print("file [%s] does not exist"%account)
        exit()

def update_file(account):
    account_data = load_file(account)
    print(account_data)
    account_data[‘status‘] =1
    print(account_data)
    file_name = ‘%s.json‘ % account
    with open(file_name, ‘w‘, encoding=‘utf-8‘) as f:
        acc_data = json.dump(account_data, f)

user_login()

  

import json,time

count = 0
data = json.load(open(‘1234.json‘,‘r‘,encoding=‘utf-8‘))
_username = ‘1234.json‘
_password = data[‘password‘]
time_json = time.mktime(time.strptime(data[‘expire_date‘],‘%Y-%m-%d‘))
time_now = time.time()
while count < 3:
    if data[‘status‘] == 1:
        print(‘賬號已鎖定!‘)
        break
    elif time_now > time_json:
        print(‘賬號已過期!‘)
        break
    else:
        name = input(‘name:‘).strip()
        password = input(‘password:‘).strip()
        if name == _username and password == _password:
            print(‘登錄成功!‘)
            break
        else:
            print(‘請重新輸入‘)
        count += 1
else:
    data[‘status‘] = 1
    json.dump(data,open(‘1234.json‘,‘w‘,encoding=‘utf-8‘))

  

31,把第30題三次驗證的密碼進行hashlib加密處理。即:json文件保存為md5的值,然後用md5的值進行驗證

{"expire_date": "2019-03-01", "id": 1234, "status": 0, "pay_day": 22, "password": "900150983cd24fb0d6963f7d28e17f72"}
import json,time,hashlib

count = 0
data = json.load(open(‘1234.json‘,‘r‘,encoding=‘utf-8‘))
_username = ‘1234.json‘
_password = data[‘password‘] #abc
time_json = time.mktime(time.strptime(data[‘expire_date‘],‘%Y-%m-%d‘))
time_now = time.time()
while count < 3:
    if data[‘status‘] == 1:
        print(‘賬號已鎖定!‘)
        break
    elif time_now > time_json:
        print(‘賬號已過期!‘)
        break
    else:
        name = input(‘name:‘).strip()
        password = input(‘password:‘).strip()
        if name == _username:
            m = hashlib.md5()
            m.update(password.encode())
            if m.hexdigest() == _password:
                print(‘登錄成功!‘)
                break
        else:
            print(‘請重新輸入‘)
        count += 1
else:
    data[‘status‘] = 1
    json.dump(data,open(‘1234.json‘,‘w‘,encoding=‘utf-8‘))

  

32,最近luffy買了個tesla,通過轉賬的形式,並且支付了5%的手續費,tesla價格為75萬。文件為json,請用程序實現該轉賬行為。
需求如下:

(1) 目錄結構為:

.
├── account
│   ├── luffy.json
│   └── tesla.json
└── bin
      └── start.py

  當執行start.py時,出現交互窗口

   ------- Luffy Bank ---------
  1.  賬戶信息
  2.  轉賬

  • 選擇1 賬戶信息 顯示luffy的當前賬戶余額。
  • 選擇2 轉賬 直接扣掉75萬和利息費用並且tesla賬戶增加75萬

  

33,對上題增加一個需求:提現。,目錄結構如下:

.
├── account
│   └── luffy.json
├── bin
│   └── start.py
└── core
   └── withdraw.py

當執行start.py時,出現交互窗口

   ------- Luffy Bank ---------
1.  賬戶信息
2.  提現

  

  • 選擇1 賬戶信息 顯示luffy的當前賬戶余額和信用額度。
  • 選擇2 提現 提現金額應小於等於信用額度,利息為5%,提現金額為用戶自定義。

34,嘗試把上一章的驗證用戶登陸的裝飾器添加到提現和轉賬的功能上。

35,對第34題的用戶轉賬、登錄、提現操作均通過logging模塊記錄日誌,日誌文件位置如下

 .
 ├── account
 │   └── luffy.json
 ├── bin
 │   └── start.py
 └── core
 |   └── withdraw.py
 └── logs
     └── bank.log

  

30-35題的答案見:http://www.cnblogs.com/wj-1314/p/7501455.html

36,簡述ascii,unicode,utf-8,gbk之間的關系

unicode     包含所有國家的字符編碼
utf-8         可變長的字符編碼,英文表示一個字節,中文表示三個字節
ascii          美國標誌信息交換代碼,是基於拉丁字母的一套電腦編碼系統。
                主要用於顯示現代英語和其他西歐語言,一個字符占一個字節            
gbk           全稱,漢字內碼擴展規範,一個字符占用兩個字節

37,閱讀代碼,請寫出執行結果

1 a = "alex"
2 b = a.capitalize()
3 print(a)
4 print(b)

  

執行結果:

1 alex
2 Alex

38,寫代碼,有如下變量,請按照要求實現每個功能

name="aleX"

  • a.移除 name 變量對應的值兩邊的空格,並輸入移除後的內容
  • b.判斷 name 變量對應的值是否以"al"開頭,並輸出結果
  • c.判斷 name 變量對應的值是否以"X"結尾,並輸出結果
  • d.將 name 變量對應的值中的“l”替換為“p”,並輸出結果
  • e.將 name 變量對應的值根據“l”分割,並輸出結果。
  • f.請問,上一題e分割之後得到值是什麽類型(可選)
  • g.將 name 變量對應的值變大寫,並輸出結果
  • h.將 name 變量對應的值變小寫,並輸出結果
  • i.請輸出 name 變量對應的值的第 2 個字符?
  • j.請輸出 name 變量對應的值的前 3 個字符?
  • k.請輸出 name 變量對應的值的後 2 個字符?
  • l.請輸出 name 變量對應的值中“e”所在索引位置?
  • m.獲取子序列,僅不包含後一個字符。如:oldboy則獲取oldbo;root則獲取roo

a.移除 name 變量對應的值兩邊的空格,並輸入移除後的內容
print(name.strip()) #aleX

b.判斷 name 變量對應的值是否以"al"開頭,並輸出結果
print(name.startswith(‘al‘)) #False

c.判斷 name 變量對應的值是否以"X"結尾,並輸出結果
print(name.endswith(‘X‘)) #False

d.將 name 變量對應的值中的“l”替換為“p”,並輸出結果
print(name.replace(‘l‘,‘p‘)) #apeX

e.將 name 變量對應的值根據“l”分割,並輸出結果。
print(name.split(‘l‘)) #[‘a‘, ‘eX‘]

f.請問,上一題e分割之後得到值是什麽類型(可選)
print(type(name.split(‘l‘))) #<class ‘list‘>

g.將 name 變量對應的值變大寫,並輸出結果
print(name.upper()) #ALEX

h.將 name 變量對應的值變小寫,並輸出結果
print(name.lower()) #alex

i.請輸出 name 變量對應的值的第 2 個字符?
print(name[1:2]) #l

j.請輸出 name 變量對應的值的前 3 個字符?
print(name[:3]) #ale

k.請輸出 name 變量對應的值的後 2 個字符?
print(name[-2:]) #eX

l.請輸出 name 變量對應的值中“e”所在索引位置?
print(name.index(‘e‘)) #2

m.獲取子序列,僅不包含後一個字符。如:oldboy則獲取oldbo;root則獲取roo
n1 = "oldboy"
n2 = n1.strip(‘y‘)
print(n2)  #oldbo

39,字符串是否可以叠代對象?如可以請使用for循環每一個元素?

是
name = ‘study‘
for i in name:
    print(i)

# 結果:
# s
# t
# u
# d
# y

40,什麽是叠代?

利用for循環來遍歷一個列表(list)或元祖(tuple),將值依次取出,這種方法我們稱為叠代
利用for語句叠代字符串,創建一個字符串,name = "deidai",然後用for語句進行叠代。

41,請用代碼實現:

a,利用下劃線將列表的每一個元素拼接成字符串,strr="alexericrain"

strr = "alexericrain"
pinjie = ‘_‘.join(strr)
print(type(pinjie),pinjie)
# <class ‘str‘> a_l_e_x_e_r_i_c_r_a_i_n

b.利用下劃線將列表的每一個元素拼接成字符串,li=[‘alex‘,‘eric‘,‘rain‘]

li = [‘alex‘,‘eric‘,‘rain‘]
pinjie = ‘_‘.join(li)
print(type(pinjie),pinjie)
# <class ‘str‘> alex_eric_rain

42,開發敏感詞語過濾程序,提示用戶輸入內容,如果用戶輸入的內容中包含特殊的字符:
如:"蒼老師"“東京熱”,則將內容替換為***

sentence_input  = input("請輸入:")
sensitive_varcabulary1 = str.maketrans("蒼老師",‘***‘)
sensitive_varcabulary2 = str.maketrans("東京熱",‘***‘)
new_sentence = sentence_input.translate(sensitive_varcabulary1).translate(sensitive_varcabulary2)
print(new_sentence)
# 請輸入:dads大大的蒼老師
# dads大大的***

43, 請分別介紹文件操作中不同的打開方式之間的區別:

44,什麽是裝飾器?寫一個裝飾器,可以打印輸出方法執行時長的信息。
  裝飾器模式(Decorator Pattern)允許向一個現有的對象添加新的功能,同時又不改變其結構。這種類型的設計模式屬於結構型模式,它是作為現有的類的一個包裝。
  這種模式創建了一個裝飾類,用來包裝原有的類,並在保持類方法簽名完整性的前提下,提供了額外的功能。
  我們通過下面的實例來演示裝飾器模式的用法。其中,我們將把一個形狀裝飾上不同的顏色,同時又不改變形狀類。

import time

def timer(func):
def decor(*args):

start_time = time.time()
func(*args)
end_time = time.time()
d_time = end_time - start_time
print("run the func use : ", d_time)
return decor

@timer #printSth = timer(printSth) -> printSth = decor
def printSth(str, count):
for i in range(count):
print("%d hello,%s!"%(i,str))

printSth("world", 1000000)#run the func use : 4.414000034332275

  

45:編寫3個函數,每個函數執行的時間是不一樣的,

  提示:可以使用time.sleep(2),讓程序sleep 2s或更多,

46:編寫裝飾器,為每個函數加上統計運行時間的功能

  提示:在函數開始執行時加上start=time.time()就可紀錄當前執行的時間戳,函數執行結束後在time.time() - start就可以拿到執行所用時間

47:編寫裝飾器,為函數加上認證的功能,即要求認證成功後才能執行函數

48:編寫裝飾器,為多個函數加上認證的功能(用戶的賬號密碼來源於文件),要求登錄成功一次,後續的函數都無需再輸入用戶名和密碼

  提示:從文件中讀出字符串形式的字典,可以用eval(‘{"name":"egon","password":"123"}‘)轉成字典格式

49,判斷下列數據類型是可叠代對象or叠代器

s=‘hello‘
l=[1,2,3,4]
t=(1,2,3)
d={‘a‘:1}
set={1,2,3}
f=open(‘a.txt‘)

  

s=‘hello‘     #字符串是可叠代對象,但不是叠代器
l=[1,2,3,4]     #列表是可叠代對象,但不是叠代器
t=(1,2,3)       #元組是可叠代對象,但不是叠代器
d={‘a‘:1}        #字典是可叠代對象,但不是叠代器
set={1,2,3}     #集合是可叠代對象,但不是叠代器
f=open(‘test.txt‘) #文件是可叠代對象,但不是叠代器

#如何判斷是可叠代對象,只有__iter__方法,執行該方法得到的叠代器對象。
# 及可叠代對象通過__iter__轉成叠代器對象
from collections import Iterator  #叠代器
from collections import Iterable  #可叠代對象

print(isinstance(s,Iterator))     #判斷是不是叠代器
print(isinstance(s,Iterable))       #判斷是不是可叠代對象

#把可叠代對象轉換為叠代器
print(isinstance(iter(s),Iterator))

  

python 對模塊的應用你還得練點這些