Python中常用功能的實(shí)現(xiàn)代碼分享
1. 新建文件夾
if not os.path.exists(feature_dir): os.makedirs(feature_dir)
2. 后臺(tái)運(yùn)行并保存log
nohup python -u test.py > test.log 2>&1 & #最后的&表示后臺(tái)運(yùn)行 #2 輸出錯(cuò)誤信息到提示符窗口 #1 表示輸出信息到提示符窗口, 1前面的&注意添加, 否則還會(huì)創(chuàng)建一個(gè)名為1的文件 #最后會(huì)把日志文件輸出到test.log文件 #查看 tail -f test.log#如果要實(shí)時(shí)查看日志文件使用命令 cat test.log#查看全部輸出使用命令
3. 文件讀取
###1.python #讀寫txt with open(r'./data/user_dict.txt','r',encoding='utf-8') as f: data = f.readlines() #追加模式 with open(r'./data/user_dict.txt','a',encoding='utf-8') as f: t = '你好' f.write('\n'+t) #按行讀取tsv / 內(nèi)存大可以直接.readlines() with open('./data/train.tsv',encoding = 'utf-8') as file: line = file.readline() limit = 0 while line and limit<10: print(line) limit+=1 line = file.readline() ###2.json 存儲(chǔ)dict x = {..} #save with open(r"./x.json",'w') as f: json.dump(x, f, ensure_ascii=False) #單行 print('done') ## 格式化 with open(r"result.json", 'w') as f: json.dump(res, f, ensure_ascii=False, indent=4) #read with open(r"./x.json",'r') as f: x = json.loads(f.readlines()[0]) #讀取格式化后的多行json with open(r"./x.json",'r') as f: x = json.load(f) ###3.numpy 存儲(chǔ)list x = [x,] np.save("./././x.npy",x) x = np.load(r"./././x.npy") ###4.pandas #read xlsx data = pd.read_excel(r'xxxx.xlsx','Sheet1') #dict to df result = {x:1,y:2,..} df = pd.DataFrame(list(result.items()), columns=['key','value']) #save df df.to_csv(r"./result.csv", index=False,header=True) #read df = pd.read_csv(r'./result.csv',encoding = 'gbk')
4. 字符串判斷
s.islower() #判斷是否所有字符小寫 s.isupper() #判斷是否所有字符大寫 s.isalpha() #判斷是否所有字符為字母 s.isalnum() #判斷是否所有字符為字母或數(shù)字 s.isdigit() #判斷是否所有字符為數(shù)字 s.istitle() #判斷是否所有字符為首字母大寫
5. 統(tǒng)計(jì)list元素出現(xiàn)次數(shù)
from collections import Counter x = [1,2,3,2] y= '1232' Counter(x) #>>Counter({2: 2, 1: 1, 3: 1}) #就是一個(gè)dict Counter(y) #>>Counter({'2': 2, '1': 1, '3': 1}) Counter('1232')['2'] #>>2
6. timestamp 轉(zhuǎn)換標(biāo)準(zhǔn)時(shí)間
# 把時(shí)間處理 以找到登陸時(shí)間 import time def timestamp_datetime(value): format = '%Y-%m-%d %H:%M:%S' # value為傳入的值為時(shí)間戳(整形),如:1332888820 value = time.localtime(value) ## 經(jīng)過localtime轉(zhuǎn)換后變成 ## time.struct_time(tm_year=2012, tm_mon=3, tm_mday=28, tm_hour=6, tm_min=53, tm_sec=40, tm_wday=2, tm_yday=88, tm_isdst=0) # 最后再經(jīng)過strftime函數(shù)轉(zhuǎn)換為正常日期格式。 dt = time.strftime(format, value) return dt def datetime_timestamp(dt): #dt為字符串 #中間過程,一般都需要將字符串轉(zhuǎn)化為時(shí)間數(shù)組 time.strptime(dt, '%Y-%m-%d %H:%M:%S') ## time.struct_time(tm_year=2012, tm_mon=3, tm_mday=28, tm_hour=6, tm_min=53, tm_sec=40, tm_wday=2, tm_yday=88, tm_isdst=-1) #將"2012-03-28 06:53:40"轉(zhuǎn)化為時(shí)間戳 s = time.mktime(time.strptime(dt, '%Y-%m-%d %H:%M:%S')) return int(s) d = datetime_timestamp('2015-03-30 16:38:20') print(d) s = timestamp_datetime(1427704700) print(s)
7. 排序
#方法1.用List的成員函數(shù)sort進(jìn)行排序,在本地進(jìn)行排序,不返回副本 #方法2.用built-in函數(shù)sorted進(jìn)行排序(從2.4開始),返回副本,原始輸入不變 listX = [[1,4],[2,5],[3,3]] sorted(listX, key=lambda x : x[1]) #>>[[3, 3], [1, 4], [2, 5]] ### 兩個(gè)list按同意順序排序 list1 = [1, 2, 3, 4, 15, 6] list2 = ['a', 'b', 'c', 'd', 'e', 'f'] c = list(zip(list1,list2)) c.sort(reverse=True) #降序du list1[:],list2[:] = zip(*c) print(list1,list2)
8. 文件路徑獲取
path1 = os.getcwd() #最外層執(zhí)行的main.py的路徑 path2 = os.path.dirname(os.path.realpath(__file__)) #當(dāng)前py文件的絕對(duì)路徑
9. 同一行刷新打印
print("\r",object,end="",flush=True) #e.g. for i,img_name in enumerate(img_names): print("\r",str(i)+"/"+str(len(img_names)),end="",flush=True)
10. PIL resize比opencv更清晰
img = cv2.imread("000000000113_0.jpg") img = Image.fromarray(img) img = img.resize((192,192)) img = np.array(img)
11. base64轉(zhuǎn)opencv
def imgToBase64(img_array): # 傳入圖片為RGB格式numpy矩陣,傳出的base64也是通過RGB的編碼 img_array = cv2.cvtColor(img_array, cv2.COLOR_RGB2BGR) #RGB2BGR,用于cv2編碼 encode_image = cv2.imencode(".jpg", img_array)[1] #用cv2壓縮/編碼,轉(zhuǎn)為一維數(shù)組 byte_data = encode_image.tobytes() #轉(zhuǎn)換為二進(jìn)制 base64_str = base64.b64encode(byte_data).decode("ascii") #轉(zhuǎn)換為base64 return base64_str def base64ToImg(base64_str): # 傳入為RGB格式下的base64,傳出為RGB格式的numpy矩陣 byte_data = base64.b64decode(base64_str)#將base64轉(zhuǎn)換為二進(jìn)制 encode_image = np.asarray(bytearray(byte_data), dtype="uint8")# 二進(jìn)制轉(zhuǎn)換為一維數(shù)組 img_array = cv2.imdecode(encode_image, cv2.IMREAD_COLOR)# 用cv2解碼為三通道矩陣 img_array = cv2.cvtColor(img_array, cv2.COLOR_BGR2RGB)# BGR2RGB return img_array
到此這篇關(guān)于Python中常用功能的實(shí)現(xiàn)代碼分享的文章就介紹到這了,更多相關(guān)Python常用功能內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python使用xlrd實(shí)現(xiàn)讀取合并單元格
這篇文章主要介紹了Python使用xlrd實(shí)現(xiàn)讀取合并單元格,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-07-07python實(shí)現(xiàn)倒計(jì)時(shí)小工具
這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)倒計(jì)時(shí)小工具,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-07-07Tensorflow設(shè)置顯存自適應(yīng),顯存比例的操作
今天小編就為大家分享一篇Tensorflow設(shè)置顯存自適應(yīng),顯存比例的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-02-02詳解使用python繪制混淆矩陣(confusion_matrix)
這篇文章主要介紹了詳解使用python繪制混淆矩陣(confusion_matrix),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-07-07python 實(shí)現(xiàn)在無序數(shù)組中找到中位數(shù)方法
這篇文章主要介紹了python 實(shí)現(xiàn)在無序數(shù)組中找到中位數(shù)方法,具有很好對(duì)參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-03-03