1. 程式人生 > 其它 >11屆省賽python試題 G: 重複字串

11屆省賽python試題 G: 重複字串

技術標籤:python函式篇python

常用模組

時間模組

# time
三種格式:
		# time.time()
            1.時間戳:從1970年到現在,經理過的秒數
                time.time()
         # time.strftime()  當前時間  # 等同於time.asctime() --- 不用寫符號
            %Y 年 - %m 月 - %d 日 - %H 時 - %M 分 - %S 秒 - %p 上下午
            %X 時分秒
            2.格式化的字串形式:2020-12-07
151821 import time res = time.strftime('%Y-%m-%d %H:%M:%S %p') print(res) 2020-12-07 15:22:22 PM # time.localtime() 當前時間 3.結構化時間 import time res = time.localtime() print(res) time.struct_time(
tm_year=2020, tm_mon=12, tm_mday=7, tm_hour=15, tm_min=30, tm_sec=27, tm_wday=0, tm_yday=342, tm_isdst=0) # 應用場景 時間戳:用於計算間隔間隔的計算 格式化時間:用於展示時間 結構化時間:獲取當前時間的詳細資訊 # datetime # datetime.datetime.now() 1.格式化時間 import datetime res = datetime.datetime.now() print(res) 2020
-12-07 15:45:42.230244 2.時間的加減 格式化時間+datetime.timedelta(days=3) # 時間模組需要掌握的操作 1.時間格式的轉換 import time # 時間戳---》》結構化時間 res = time.time() str_time = time.localtime(res) print(str_time) time.struct_time(tm_year=2020, tm_mon=12, tm_mday=7, tm_hour=16, tm_min=4, tm_sec=22, tm_wday=0, tm_yday=342, tm_isdst=0) # 真正掌握的是時間戳與格式化字串時間的互轉 import time res = time.strftime('%Y-%m-%d %H:%M:%S') # 格式化字串時間 a = time.strptime(res,'%Y-%m-%d %H:%M:%S') # 格式化時間==》》》結構化時間 b = time.mktime(a) # 結構化時間==》》》時間戳 c = b+30*24*60*60 # 對時間戳進行增減操作 d = time.localtime(c) # 時間戳==》》》結構化時間 e = time.strftime('%Y-%m-%d %H:%M:%S',d) # 結構化時間==》》》格式化字串時間 print(res) print(e) # 總結 時間戳 ==》》 結構化時間 ==》》 格式化時間 time.localtime() time.strftime() # localtime() 中國時間 time.gmtime() time.strftime() # gmtime() 世界時間 格式化字元時間 ====》》 結構化時間 ====》》 時間戳 time.strptime() time.mktime() # 用法總結 import time time.time() # 獲取當前時間戳 time.sleep() # 程式臨時停止時間,單位S time.mktime() # 從結構時間==》》》時間戳 time.strftime() # 格式化字元時間,格式:年月日 %Y-%m-%d 時分秒: %H:%M:%S 上下午 %P 簡寫:年月日 %F 時分秒 %X time.localtime() # 結構化時間 time.asctime() # 獲取當前格式化字串時間,無需格式化引數 time.strptime() # 從結構化時間==>>> 格式化字串時間 res = time.gmtime() # 獲取世界時間,結構化時間

json&pickle

# 什麼是序列化
	# 所有的語言都有一種通用的特定格式,通過特定格式進行跨平臺性
1.指的是把記憶體的資料型別,轉換成一種特定的格式
2.該格式的內容可用於儲存,或者傳輸給其他平臺使用
3.記憶體中的資料型別---》序列化----》》特定的格式(json格式,pickle格式)
{'name':'sun'}--->>str({'name':'sun'})--->>>"{'name':'sun'}"
4.特定的格式----》》》反序列化---》》》記憶體中的資料型別
"{'name':'sun'}"--->>eval("{'name':'sun'}")--->>>{'name':'sun'}

# 為何序列化,反序列化?
1.用來儲存在硬碟==》》用於存檔
2.傳輸給其他平臺==》》跨平臺資料互動
	一種專用的特定格式,只用於一種平臺  # pickle 用於存檔,自己跟自己玩
	python--》》---(特定格式)---》》----java  # json  針對跨平臺性,資料互動
    
# json 的應用
1.json.dumps()  # 序列化
import json
info = ['name', 18, True]
res = json.dumps(info)
print(res,type(res))  # ["name", 18, true] <class 'str'>

2.json.loads()  # 反序列化
new_res = json.loads(res)
print(new_res,type(new_res))  # ['name', 18, True] <class 'list'>

3.json.dump(資料內容,f檔案控制代碼)  # 序列化的資料寫入檔案
import json
with open(r'a.txt', mode='wt', encoding='utf-8') as f:
    json.dump(info, f)
	
4.json.load(f檔案控制代碼)  # 反序列化的資料讀入檔案
import json
with open(r'a.txt', mode='wt', encoding='utf-8') as f:
    json.load( f )

    
# 將序列化寫入檔案的簡單方法
import json
with open(r'a.txt',mode='wt',encoding='utf-8') as f:
    json.dump( 序列化內容 ,f )  # 序列化的內容寫入檔案
    
with open(r'a.txt',mode='rt',encoding='utf-8') as f:
    json.load( f )  # 反序列化的內容讀入檔案
# 總結
1.序列化得到的結果時字串格式  # 從硬碟讀入記憶體,是字串	
2.json格式是所有語言通用的資料型別,但是如果不通用的資料型別,json就不可以轉換

xml ,shelve 模組

# xml是實現不同語言或程式之間驚醒資料互動的協議,跟json差不多,但json使用起來更簡單,不過,古時候,在json還沒有誕生的黑暗年代,大家只能選擇用xml,至今很多傳統公司入金融行業的很多系統的介面還是主要是xml

# xml的格式如下,就是通過<>節點來區別資料結構的:
<?xml version="1.0"?>
<data>
    <country name="Liechtenstein">
        <rank updated="yes">2</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
    <country name="Singapore">
        <rank updated="yes">5</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <neighbor name="Malaysia" direction="N"/>
    </country>
    <country name="Panama">
        <rank updated="yes">69</rank>
        <year>2011</year>
        <gdppc>13600</gdppc>
        <neighbor name="Costa Rica" direction="W"/>
        <neighbor name="Colombia" direction="E"/>
    </country>
</data>

# xml協議在各個語言裡的都 是支援的,在python中可以用以下模組操作xml:
print(root.iter('year')) #全文搜尋
print(root.find('country')) #在root的子節點找,只找一個
print(root.findall('country')) #在root的子節點找,找所有

# code_view
#遍歷xml文件
for child in root:
    print('========>',child.tag,child.attrib,child.attrib['name'])
    for i in child:
        print(i.tag,i.attrib,i.text)
 
#只遍歷year 節點
for node in root.iter('year'):
    print(node.tag,node.text)
#---------------------------------------

import xml.etree.ElementTree as ET
 
tree = ET.parse("xmltest.xml")
root = tree.getroot()
 
#修改
for node in root.iter('year'):
    new_year=int(node.text)+1
    node.text=str(new_year)
    node.set('updated','yes')
    node.set('version','1.0')
tree.write('test.xml')
 
 
#刪除node
for country in root.findall('country'):
   rank = int(country.find('rank').text)
   if rank > 50:
     root.remove(country)
 
tree.write('output.xml')


# shelve 模組
shelve模組比pickle模組簡單,只有一個open函式,返回類似字典的物件,可讀可寫;key必須為字串,而值可以是python所支援的資料型別

# code——view
import shelve

f=shelve.open(r'sheve.txt')
# f['stu1_info']={'name':'egon','age':18,'hobby':['piao','smoking','drinking']}
# f['stu2_info']={'name':'gangdan','age':53}
# f['school_info']={'website':'http://www.pypy.org','city':'beijing'}

print(f['stu1_info']['hobby'])
f.close()

隨機模組

# random 用來取隨機值
random.random()  # 預設隨機從(0,1)取小數,大於0,小於1  # 預設不加引數
random.uniform(13)  # 隨機從(1,3)取小數,大於1,小於3
random.randint(1,10)  # 隨機從[1,10]取整數,大於等於1,小於等於10
random.randrange(1,10)  # 隨機從[1,10)取整數,大於等於1,小於10
random.choice([1,2,3,4,5,6])  # 隨機從[1,2,3,4,5,6]取出一個數
random.sample([1,2,3,4,5,6],2)  # 隨機從[1,2,3,4,5,6]取出2個數  # sample 樣本

list1 = [1,5,7,9]
random.shuffle(list1)  # 隨機打亂list1順序  # shuffle 洗牌

# 應用:隨機驗證碼
import random

def random_code(size=6):
    res = ''
    for x in range(size):
        eng_num = chr(random.randint(65, 90))
        num = str(random.randint(0, 9))
        res += random.choice([eng_num, num])
    print(res)
    return res

random_code()
image-20201207193117033

os 模組

# 控制作業系統對檔案的處理
os.getcwd() 獲取當前工作目錄,即當前python指令碼工作的目錄路徑
os.chdir("dirname")  改變當前指令碼工作目錄;相當於shell下cd
os.curdir  返回當前目錄: ('.')
os.pardir  獲取當前目錄的父目錄字串名:('..')
os.makedirs('dirname1/dirname2')    可生成多層遞迴目錄
os.removedirs('dirname1')    若目錄為空,則刪除,並遞迴到上一級目錄,如若也為空,則刪除,依此類推
os.mkdir('dirname')    生成單級目錄;相當於shell中mkdir dirname
os.rmdir('dirname')    刪除單級空目錄,若目錄不為空則無法刪除,報錯;相當於shell中rmdir dirname
os.listdir('dirname')    列出指定目錄下的所有檔案和子目錄,包括隱藏檔案,並以列表方式列印
os.remove()  刪除一個檔案
os.rename("oldname","newname")  重新命名檔案/目錄
os.stat('path/filename')  獲取檔案/目錄資訊
os.sep    輸出作業系統特定的路徑分隔符,win下為"\\",Linux下為"/"
os.linesep    輸出當前平臺使用的行終止符,win下為"\t\n",Linux下為"\n"
os.pathsep    輸出用於分割檔案路徑的字串 win下為;,Linux下為:
os.name    輸出字串指示當前使用平臺。win->'nt'; Linux->'posix'
os.system("bash command")  執行shell命令,直接顯示
os.environ  獲取系統環境變數
os.path.abspath(path)  返回path規範化的絕對路徑
os.path.split(path)  將path分割成目錄和檔名二元組返回
os.path.dirname(path)  返回path的目錄。其實就是os.path.split(path)的第一個元素
os.path.basename(path)  返回path最後的檔名。如何path以/或\結尾,那麼就會返回空值。即os.path.split(path)的第二個元素
os.path.exists(path)  如果path存在,返回True;如果path不存在,返回False
os.path.isabs(path)  如果path是絕對路徑,返回True
os.path.isfile(path)  如果path是一個存在的檔案,返回True。否則返回False
os.path.isdir(path)  如果path是一個存在的目錄,則返回True。否則返回False
os.path.join(path1[, path2[, ...]])  將多個路徑組合後返回,第一個絕對路徑之前的引數將被忽略
os.path.getatime(path)  返回path所指向的檔案或者目錄的最後存取時間
os.path.getmtime(path)  返回path所指向的檔案或者目錄的最後修改時間
os.path.getsize(path) 返回path的大小

sys 模組

# 跟系統有關
1 sys.argv           命令列引數List,第一個元素是程式本身路徑,後面的引數是在直譯器終端新增的元素
2 sys.exit(n)        退出程式,正常退出時exit(0)
3 sys.version        獲取Python解釋程式的版本資訊
4 sys.maxint         最大的Int值
5 sys.path           返回模組的搜尋路徑,初始化時使用PYTHONPATH環境變數的值
6 sys.platform       返回作業系統平臺名稱

shutil 模組–瞭解

# 高階的檔案,資料夾,壓縮包處理模組
1.shutil.copyfileobj(fsrc, fdst, length)  # 將檔案內容拷貝到另一個檔案中
	shutil.copyfileobj(open('old.xml','r'), open('new.xml', 'w'))
 
2.shutil.copyfile(src, dst)  # 拷貝檔案, 目標無需存在
	shutil.copyfile('f1.log', 'f2.log') 
    
3.shutil.copymode(src, dst)  # 僅拷貝許可權。內容、組、使用者均不變
	shutil.copymode('f1.log', 'f2.log')  # 目標檔案必須存在
    
4.shutil.copystat(src, dst)  # 僅拷貝狀態的資訊,包括:mode bits, atime, mtime, flags
	shutil.copystat('f1.log', 'f2.log') #目標檔案必須存在
    
5.shutil.copy(src, dst)  # 拷貝檔案和許可權
	shutil.copy('f1.log', 'f2.log')
    
6.shutil.copy2(src, dst)  # 拷貝檔案和狀態資訊
	shutil.copy2('f1.log', 'f2.log')
    
7.shutil.ignore_patterns(*patterns)  # 遞迴的去拷貝資料夾
shutil.copytree(src, dst, symlinks=False, ignore=None)  # 遞迴的去拷貝資料夾
	shutil.copytree('folder1', 'folder2', ignore=shutil.ignore_patterns('*.pyc', 'tmp*')) #目標目錄不能存在,注意對folder2目錄父級目錄要有可寫許可權,ignore的意思是排除
    
8.shutil.rmtree(path[, ignore_errors[, onerror]])  # 遞迴的去刪除檔案
	shutil.rmtree('folder1')
    
9.shutil.move(src, dst)  # 遞迴的去移動檔案,它類似mv命令,其實就是重新命名。
	shutil.move('folder1', 'folder3')
    
10.shutil.make_archive(base_name, format,...)  # 建立壓縮包並返回檔案路徑,例如:zip、tar
    base_name: 壓縮包的檔名,也可以是壓縮包的路徑。只是檔名時,則儲存至當前目錄,否則儲存至指定路徑,
    如 data_bak                       =>儲存至當前路徑
    如:/tmp/data_bak =>儲存至/tmp/
    format:	壓縮包種類,“zip, “tar”, “bztar”,“gztar”
    root_dir:	要壓縮的資料夾路徑(預設當前目錄)
    owner:	使用者,預設當前使用者
    group:	組,預設當前組
    logger:	用於記錄日誌,通常是logging.Logger物件
   	# 列子
    #將 /data 下的檔案打包放置當前程式目錄
    import shutil
    ret = shutil.make_archive("data_bak", 'gztar', root_dir='/data')

    #將 /data下的檔案打包放置 /tmp/目錄
    import shutil
    ret = shutil.make_archive("/tmp/data_bak", 'gztar', root_dir='/data')

configparser

# 對配置檔案進行操作
# 註釋1
[section1]
k1 = v1
k2:v2
user=egon
age=18
is_admin=true
salary=31
[section2]
k1 = v1

# 匯入模組
import configparser

config=configparser.ConfigParser()
config.read('a.cfg')

#檢視所有的標題
res=config.sections() #['section1', 'section2']
print(res)

#檢視標題section1下所有key=value的key
options=config.options('section1')
print(options) #['k1', 'k2', 'user', 'age', 'is_admin', 'salary']

#檢視標題section1下所有key=value的(key,value)格式
item_list=config.items('section1')
print(item_list) #[('k1', 'v1'), ('k2', 'v2'), ('user', 'egon'), ('age', '18'), ('is_admin', 'true'), ('salary', '31')]

#檢視標題section1下user的值=>字串格式
val=config.get('section1','user')
print(val) #egon

#檢視標題section1下age的值=>整數格式
val1=config.getint('section1','age')
print(val1) #18

#檢視標題section1下is_admin的值=>布林值格式
val2=config.getboolean('section1','is_admin')
print(val2) #True

#檢視標題section1下salary的值=>浮點型格式
val3=config.getfloat('section1','salary')
print(val3) #31.0

改寫

import configparser

config=configparser.ConfigParser()
config.read('a.cfg',encoding='utf-8')


#刪除整個標題section2
config.remove_section('section2')

#刪除標題section1下的某個k1和k2
config.remove_option('section1','k1')
config.remove_option('section1','k2')

#判斷是否存在某個標題
print(config.has_section('section1'))

#判斷標題section1下是否有user
print(config.has_option('section1',''))


#新增一個標題
config.add_section('egon')

#在標題egon下新增name=egon,age=18的配置
config.set('egon','name','egon')
config.set('egon','age',18) #報錯,必須是字串


#最後將修改的內容寫入檔案,完成最終的修改
config.write(open('a.cfg','w'))