0顷编、https://jsoneditoronline.org/
0.5渡蜻、命令行裝包:
(sudo) python3 -m pip install +包名稱
pip --default-timeout=100 install -U +包名
1、program = os.path.basename(sys.argv[0]) ——當(dāng)前py文件的名字
2学歧、return? len(result)!=len(set(result)) ——判斷result里是否有重復(fù)的元素罩引,有返回True,沒(méi)有返回False
3枝笨、Python 16進(jìn)制轉(zhuǎn)10進(jìn)制:
字符串轉(zhuǎn)整數(shù):
10進(jìn)制字符串: int('10') ?==> ?10
16進(jìn)制字符串: int('10', 16) ?==> ?16
16進(jìn)制字符串: int('0x10', 16) ?==> ?16
整數(shù)之間的進(jìn)制轉(zhuǎn)換:
10進(jìn)制轉(zhuǎn)16進(jìn)制: hex(16) ?==> ?0x10
16進(jìn)制轉(zhuǎn)10進(jìn)制: int('0x10', 16) ?==> ?16
類似的還有oct()袁铐, bin()
4、list的for循環(huán)横浑,是按順序從頭遍歷的剔桨。下例加一個(gè)break就能找到value的上限了:
values_limits = [19, 49, 99, 299, 999]? #--從小到大按順序排,于是for循環(huán)遍歷是也會(huì)從19-》999徙融,只要小于就break洒缀,就能找到所在區(qū)間。
value =298
desc_data = {}
desc_data['key'] = guide_key_list[0]
if value ==0:
????desc_data['val'] ='本區(qū)縣暫無(wú)數(shù)據(jù)欺冀,敬請(qǐng)期待'
elif value > values_limits[-1]:
????desc_data['val'] = map_color_level[-1]['deta']
else:
????for i in range(len(values_limits)):
????????if value <= values_limits[i]:
????????????desc_data['val'] = map_color_level[i]['deta']
????????????break
5树绩、os.path:
python中的os.path模塊用法:
dirname()?? 用于去掉文件名,返回目錄所在的路徑
如:
>>> import os
>>> os.path.dirname('d:\\library\\book.txt')'d:\\library'
basename()?? 用于去掉目錄的路徑隐轩,只返回文件名
如:
>>> import os
>>> os.path.basename('d:\\library\\book.txt')'book.txt'
join()? ?用于將分離的各部分組合成一個(gè)路徑名
如:
>>> import os
>>> os.path.join('d:\\library','book.txt')'d:\\library\\book.txt'
split()? 用于返回目錄路徑和文件名的元組
如:
>>> import os
>>> os.path.split('d:\\library\\book.txt')('d:\\library', 'book.txt')
splitdrive()?? ?用于返回盤符和路徑字符元組
>>> import os
>>> os.path.splitdrive('d:\\library\\book.txt')('d:', '\\library\\book.txt')
splitext()??? 用于返回文件名和擴(kuò)展名元組
如:
>>> os.path.splitext('d:\\library\\book.txt')('d:\\library\\book', '.txt')
>>> os.path.splitext('book.txt')('book', '.txt')
6饺饭、顯示當(dāng)前目錄下的所有文件和文件夾:
用python實(shí)現(xiàn):
import os
path = os.listdir(os.getcwd())
? print (path)
或者這樣寫也一樣:
import os
path = os.listdir('.')
print (path)
?如果只輸出當(dāng)前文件夾下的所有文件夾:
import os
path = os.listdir(os.getcwd())
#print (path)
for p in path:
if os.path.isdir(p): #判斷是否為文件夾,如果是輸出所有文件就改成: os.path.isfile(p)
print(p)
7.
f.read() 每次讀取整個(gè)文件职车,它通常用于將文件內(nèi)容放到一個(gè)字符串變量中瘫俊。
.readline() 和 .readlines() 非常相似。它們都在類似于以下的結(jié)構(gòu)中使用:
file = open('c:\\autoexec.bat')
for line in? file.readlines():? ?// 或者直接?for line in? file:
? ? print(line)
.readline() 和 .readlines() 之間的差異是后者一次讀取整個(gè)文件悴灵,象 .read() 一樣扛芽。
.readlines() 自動(dòng)將文件內(nèi)容分析成一個(gè)行的列表,該列表可以由 Python 的 for ... in ... 結(jié)構(gòu)進(jìn)行處理积瞒。
.readline() 每次只讀取一行川尖,通常比 .readlines() 慢得多,僅當(dāng)沒(méi)有足夠內(nèi)存可以一次讀取整個(gè)文件時(shí),才應(yīng)該使用 .readline()赡鲜。
8.篩掉csv中的空值:
datas = train_data.loc[row].values[1]
if isinstance(datas,str) or not math.isnan(datas):
9. word in word_dict 等價(jià)于 word in word_dict.keys()
10. pycharm代碼格式化
ctrl+alt+L可以格式化空厌,但是和鎖屏快捷鍵沖突。?
也可以银酬,選中代碼嘲更,使用快捷鍵?ctrl+alt+i?
自己在開(kāi)發(fā)的過(guò)程中代碼太長(zhǎng)了,看起來(lái)非常不方便
設(shè)置代碼塊的自動(dòng)換行如下:
View--->Active Editor--->Use Soft Wraps
11. 加一發(fā)excel快速填充方法:
有三種快速方法:
方法一:在第一個(gè)單元格右下角雙擊揩瞪;
方法二:按住第一個(gè)單元格右下角的黑色十字往下拖
方法三:Ctrl+D快捷鍵填充
具體如下:
方法一:把鼠標(biāo)放到公式所在單元格右下角赋朦,當(dāng)鼠標(biāo)變成黑色十字時(shí),雙擊就全部填充了,但這種方法要求你復(fù)制列的前一列不能斷行宠哄,如:你在B列需要往下快速?gòu)?fù)制公式壹将,總共100行,但是A列的第51行為空毛嫉,用這種方法就只能復(fù)制公式到第50行诽俯,后面的需要你再操作一次。
方法二:把鼠標(biāo)放到公式所在單元格的右下角承粤,當(dāng)鼠標(biāo)變成黑色十字時(shí)暴区,按住鼠標(biāo)左鍵往下拖就可以了,想復(fù)制多少行都可以辛臊,沒(méi)限制仙粱,但是效率較方法一低很多。
方法三:假設(shè)你的公式在B2單元格彻舰,需要復(fù)制公式到B3:B999伐割,那么你先選擇包含公式單元格的所有需要復(fù)制公式的單元格(B2:B999),然后按Ctrl+D即可全部填充刃唤,這種方法有方法一的高效性隔心,又有方法二的通用性。很實(shí)用透揣。
12济炎、print('\r進(jìn)度:%.2f%%'%percent, end="") ——每次輸出都只出現(xiàn)在第一行,一直閃現(xiàn)
13辐真、json串的合并:
1)合并成list形式:
json.dump([json.load(open(src_path+'part1.json', 'r', encoding='utf-8')),
? ? ? ? ? json.load(open(src_path+'part2.json', 'r', encoding='utf-8'))], open(trg_path, 'w', encoding='utf-8'))
2)合并成dict形式:
datas = json.load(open(src_path+'part1.json', 'r', encoding='utf-8'))
datas.update(json.load(open(src_path +'part2.json', 'r', encoding='utf-8')))
json.dump(datas, open(trg_path, 'w', encoding='utf-8'))
14、文件流
file.seek()方法標(biāo)準(zhǔn)格式是:seek(offset,whence=0)
offset:開(kāi)始偏移量崖堤,也就是代表需要移動(dòng)偏移的字節(jié)數(shù)侍咱。
whence:給offset參數(shù)一個(gè)定義,表示要從哪個(gè)位置開(kāi)始偏移密幔;0代表從文件開(kāi)頭開(kāi)始算起楔脯,1代表從當(dāng)前位置開(kāi)始算起,2代表從文件末尾算起胯甩。
代碼:?
f= open('111.py','rb')
print(f.tell()) #0
f.seek(3) #默認(rèn)為零昧廷,從文件開(kāi)頭
print(f.tell()) #3
f.seek(4,1) #1為從當(dāng)前位置,移動(dòng)4個(gè)字節(jié)
print(f.tell()) #7
f.seek(-4,2) #從文件末尾算偎箫,移動(dòng)4個(gè)字節(jié)
print(f.tell()) #15
#f.tell()方法告知游標(biāo)的位置
15木柬、eval —— 把list/dict字符串轉(zhuǎn)為list/dict
16、time.time() -- 返回的是一個(gè)浮點(diǎn)數(shù)淹办,單位為秒
time.strftime("%Y-%m-%d %H:%M:%S")? --直接返回當(dāng)前時(shí)間, tuple
17眉枕、進(jìn)度條: —— 記得加end=''!!速挑!
????print('\r進(jìn)度:%.2f%% 運(yùn)行時(shí)間:%.2f秒 剩余時(shí)間:%.2f秒' % ((count *100 / n), (time1 - time0), ((time1 - time0) * (n - count) / count)), end='')? //寫在for循環(huán)里面谤牡, end=''表示末尾不換行,加空字符串
print('\n加載完畢')? //寫在for循環(huán)外面
如果想把每次的內(nèi)容輸出的話:print('\r'+str(res_dict)+'? ?進(jìn)度:%.2f%% 運(yùn)行時(shí)間:%.2f秒 剩余時(shí)間:%.2f秒' % ((count *100 / n), (time1 - time0), ((time1 - time0) * (n - count) / count)), end='')
18姥宝、calendar
calendar.monthrange(year,?month)?
返回指定年和月的第一天是星期幾翅萤,這個(gè)月總共有多少天。
例子:
#python?3.4
import?calendar
print(calendar.monthrange(2015,?11))
結(jié)果輸出如下:
(6,?30)
19腊满、獲取腳本名字:script_name = sys.argv[0].split('.')[0]? ?(去掉.py)
20套么、記錄異常
①把打印信息(異常信息)記錄到log文件:
import sys
# make a copy of original stdout route
stdout_backup = sys.stdout
# define the log file that receives your log info
log_file =open("message.log", "a")
# redirect print output to log file
sys.stdout = log_file
print("Now all print info will be written to message.log")
# any command line that you will execute
...
log_file.close()
# restore the output to initial pattern
sys.stdout = stdout_backup
print("Now this will be presented on screen")
② 用traceback功能
if weibo_infos ==0:
????script_name = sys.argv[0].split('.')[0]
????f=open('%s_traceback_info.txt'%script_name, 'a', encoding='utf-8')
????f.write(str(time.strftime("%Y-%m-%d %H:%M:%S"))+"? gov_id=%d" % gov_id+'\n')
????traceback.print_exc(file=f)
????f.write('\n')
????f.close()
????return 0, 0
③logging??? —— 還不會(huì),有機(jī)會(huì)研究一下
21糜烹、Python之list對(duì)應(yīng)元素求和:
方法一:
利用numpy模塊求解
importnumpy as np
a =np.array([1,2,3])
b =np.array([2,3,4])
c =np.array([3,4,5])
print(a+b+c)
需要注意的是违诗,a+b+c后的類型為numpy.ndarray.
方法二:
利用numpy模塊的sum()函數(shù)進(jìn)行求解。
importnumpy as np
a =[1,2,3]
b =[2,3,4]
c =[3,4,5]
print(np.sum([a,b,c], axis =0))
其中的axis參數(shù)表示縱向求和疮蹦。
22诸迟、locals() & globals()? &? attrs ???
>>>def runoob(arg): # 兩個(gè)局部變量:arg、z
????????... z = 1
????????... print (locals())...
>>> runoob(4)
? ? ? ?{'z': 1, 'arg': 4}? ? ? # 返回一個(gè)名字/值對(duì)的字典
23愕乎、FTP匿名登錄(ue)記得設(shè)置——user:anonymous阵苇;pwd:12345
24、set()去重后保持原list的順序:
mailto = ['cc', 'bbbb', 'afa', 'sss', 'bbbb', 'cc', 'shafa']
addr_to = list(set(mailto))
addr_to.sort(key = mailto.index)
25感论、shutil.rmtree("E:\\test\\b")
可以發(fā)現(xiàn)b文件夾連同下面的文件都消失了绅项。
26、for循環(huán) 迭代器
27掀亥、判斷變量類型:isinstance(a,tuple) —— 判斷變量a是否為元組類型
28、一句話迭代取值:
rows = [{'a': 1, 'b': 2, 'c': 0}, {'a': 2, 'b': 3, 'c': 0}]
寫法一:[i['a'] for i in rows if i['b'] == 3]? ?√
寫法二:[i['a'] if i['b'] == 3 for i in rows]? ?×? ?—— for前面必須要有else !!!
神奇之處在于妥色,if的位置不一樣搪花,值的取法要求也不一樣~~~
29、
30撮竿、
31、Logging 多模塊共用:? —— Python代碼的方式試過(guò)了笔呀,配置文件的方式之后了解一下幢踏。
32凿可、sorted: —— 排序
points =sorted(points, key=lambda x:x[0], reverse=True)
33惑折、Python自動(dòng)打開(kāi)網(wǎng)頁(yè)
34授账、Python 模擬點(diǎn)擊網(wǎng)頁(yè) / 清緩存 / 操作瀏覽器
https://blog.csdn.net/weixin_42551465/article/details/80817552
https://blog.csdn.net/zwq912318834/article/details/79215400?utm_source=blogxgwz8
https://blog.csdn.net/chengxuyuanyonghu/article/details/79154468
35、logging處理流程:【注意filter和setLevel的區(qū)別】
Filters?can be used by?Handlers?and?Loggers?for more sophisticated filtering than is provided by levels. The base filter class only allows events which are below a certain point in the logger hierarchy. For example, a filter initialized with ‘A.B’ will allow events logged by loggers ‘A.B’, ‘A.B.C’, ‘A.B.C.D’, ‘A.B.D’ etc. but not ‘A.BB’, ‘B.A.B’ etc. If initialized with the empty string, all events are passed.
class?logging.Filter(name='')
Returns an instance of the?Filter?class. If?name?is specified, it names a logger which, together with its children, will have its events allowed through the filter. If?name?is the empty string, allows every event.
filter(record)
Is the specified record to be logged? Returns zero for no, nonzero for yes. If deemed appropriate, the record may be modified in-place by this method.
Note that filters attached to handlers are consulted before an event is emitted by the handler, whereas filters attached to loggers are consulted whenever an event is logged (using?debug(),?info(), etc.), before sending an event to handlers. This means that events which have been generated by descendant loggers will not be filtered by a logger’s filter setting, unless the filter has also been applied to those descendant loggers.
You don’t actually need to subclass?Filter: you can pass any instance which has a?filter?method with the same semantics.
Although filters are used primarily to filter records based on more sophisticated criteria than levels, they get to see every record which is processed by the handler or logger they’re attached to: this can be useful if you want to do things like counting how many records were processed by a particular logger or handler, or adding, changing or removing attributes in the LogRecord being processed. Obviously changing the LogRecord needs to be done with some care, but it does allow the injection of contextual information into logs?
36、【logger的基本用法】:
37粗卜、dict按照values排序:
sorted(d.items(),key=lambda x:x[1])
38屋确、求list中出現(xiàn)次數(shù)最多的元素:
a = [1,4,2,3,2,3,4,2]
from collections import Counter
print(Counter(a).most_common(1))
輸出:[(2, 3)]? —— 表示2出現(xiàn)了3次
39、numpy中有一些常用的用來(lái)產(chǎn)生隨機(jī)數(shù)的函數(shù)续扔,randn()和rand()就屬于這其中攻臀。
numpy.random.randn(d0, d1, …, dn)是從標(biāo)準(zhǔn)正態(tài)分布中返回一個(gè)或多個(gè)樣本值。
numpy.random.rand(d0, d1, …, dn)的隨機(jī)樣本位于[0, 1)中纱昧。
40刨啸、獲取當(dāng)前的函數(shù)名
41、通過(guò)函數(shù)名(字符串)來(lái)調(diào)用函數(shù):https://blog.csdn.net/mrqingyu/article/details/84403924
【四種方法】:
法一:eval()
法二:locals()和globals()
法三:getattr()
法四:標(biāo)準(zhǔn)庫(kù)operator下的methodcaller函數(shù)
42识脆、獲取當(dāng)前運(yùn)行的函數(shù)名:http://www.cnblogs.com/paranoia/p/6196859.html
43设联、合并兩個(gè)dict
注:后面的dict會(huì)覆蓋前一個(gè)dict中重復(fù)的鍵值
44、python .format() :它通過(guò){}和:來(lái)代替?zhèn)鹘y(tǒng)%方式:https://www.cnblogs.com/benric/p/4965224.html
可以不用指定 %d 還是 %f 之類的
45灼捂、re.escape(pattern)
轉(zhuǎn)義?pattern?中的特殊字符离例。如果你想對(duì)任意可能包含正則表達(dá)式元字符的文本字符串進(jìn)行匹配,它就是有用的悉稠。