Python學習隨筆
1.自然排序算法:natsort模塊,對相似文件名排序非常有效

In [1]: from natsort import natsorted
In [2]: s = ["image10","image20","image1","image2","image3"]
In [3]: natsorted(s)
Out[3]: ['image1', 'image2', 'image3', 'image10', 'image20']
2.巧妙使用format函數進行進制轉換(b,o,d,x),某些情況下使用更Pythonic
In [1]: "{:08b}".format(254)
Out[1]: '11111110'
In [2]: "{:08o}".format(254)
Out[2]: '00000376'
In [3]: "{:04X}".format(254)
Out[3]: '00FE'
PS:將IP地址轉換為十進制只需要用一行代碼即可:int(''.join(["{:08b}".format(num) for num in map(int,ip.split('.'))]),2)
也可以用f''這樣的形式進行轉換,如:
In [1]: f'{254:08b}'
Out[1]: '11111110'
In [2]: f'{254:08o}'
Out[2]: '00000376'
In [3]: f'{254:04X}'
Out[3]: '00FE'
將IP地址轉換為十進制
int(''.join([f"{num:08b}" for num in map(int,ip.split('.'))]),2)
3.str模塊的title函數與string模塊的capwords函數
In [1]: import string
In [2]: S = "hello???????? world"
In [3]: S.title()
Out[3]: 'Hello???????? World'
In [4]: string.capwords(S)
Out[4]: 'Hello World'
4.使用glob模塊進行文件搜索
In [1]: import glob
In [2]: glob.glob("*.py")?? #獲取當前目錄下的所有py文件,不搜索子目錄
In [3]: glob.glob("D:\**",recursive=True)?? #搜索D盤目錄下所有文件
5.使用chardet檢測字符編碼
import chardet
def get_file_context(file):
#讀取文本
with open(file,'rb') as fp:
scline = fp.read()
encoding = chardet.detect(scline)['encoding']
return scline.decode(encoding)
6.獲取當前文件所在目錄:
dirname?? = os.path.dirname(__file__)?? #當前文件所在目錄
work_dir? = os.getcwd()???????????????? #當前進程所在工作目錄
7.requests庫的get與post函數
get(url, params=None, **kwargs)
Sends a GET request.
:param url: URL for the new :class:`Request` object.
:param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:return: :class:`Response
:rtype: requests.Response
post(url, data=None, json=None, **kwargs)
Sends a POST request.
:param url: URL for the new :class:`Request` object.
:param data: (optional) Dictionary (will be form-encoded), bytes, or file-like object to send in the body of the :class:`Request`.
:param json: (optional) json data to send in the body of the :class:`Request`.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:return: :class:`Response
:rtype: requests.Response
Response.status_code:響應狀態碼
Response.raw:原始響應體,使用r.raw.read()讀取
Response.content:字節方式的響應體,需要進行解碼
Response.text:字符串方式的響應體,會自動更具響應頭部的字符編碼進行解碼
Response.headers:以字典對象儲存服務器響應頭,但是這個字典比較特殊,字典鍵不區分大小寫,若鍵不存在,則返回None
Response.json():request中內置的json解碼器
Response.raise_for_status():請求失敗(非200響應),拋出異常
Response.url:獲取請求的url
Response.cookies:獲取請求后的cookies
Response.encoding:獲取編碼格式
8.requests庫的get函數關于params的用法
params = {'wd':'python',}
url??? = 'https://www.baidu.com/s'
Response = requests.get(url,params = params)
非常非常的簡單,請求的url是這樣的
In [5]: Response.url
Out[5]: 'https://www.baidu.com/s?wd=python'
PS:如果不需要提交數據,直接使用get函數來請求。
9.requests庫的post函數的用法:
在通過requests.post()進行POST請求時,傳入報文的參數有兩個,一個是data,一個是json。
data與json既可以是str類型,也可以是dict類型。
區別:
1、不管json是str還是dict,如果不指定headers中的content-type,默認為application/json
2、data為dict時,如果不指定content-type,默認為application/x-www-form-urlencoded,相當于普通form表單提交的形式
3、data為str時,如果不指定content-type,默認為application/json
4、用data參數提交數據時,request.body的內容則為a=1&b=2的這種形式,用json參數提交數據時,request.body的內容則為'{"a": 1, "b": 2}'的這種形式
PS:有遇到過post請求也可以使用params參數,并且正常返回結果
如果指定傳遞json參數,則'Content-Type':'application/json; charset=UTF-8' ,不再需要指定,已默認未application/json
文件上傳方式例舉:
files={'file':(image_file,open(image_file,'rb'),'image/png'),}
requests.post(url,headers = headers,files=files)
10.如何將010203040506070809 分割為 '01 02 03 04 05 06 07 08 09'?
import textwrap
In [4]: ' '.join(textwrap.wrap(text ='010203040506070809',width = 2))
Out[4]: '01 02 03 04 05 06 07 08 09'
如果調用re模塊
In [1]: s = '010203040506070809'
In [2]: import re
In [3]: reg = re.compile('.{1,2}')
In [4]: ' '.join(reg.findall(s))
Out[4]: '01 02 03 04 05 06 07 08 09'
11.json文件的讀取
import json
with open('res.json','r',encoding = "utf-8") as json_file:
dict_data = json.load(json_file)
12.json文件的寫入
import json
with open('res.json','w',encoding = 'utf-8') as fp:
json.dump(dict_data,fp,ensure_ascii = False)
13.yaml文件的讀取
import yaml
with open('result.yaml','r',encoding = 'utf-8') as fp:
yaml_data = yaml.load(fp)
14.yaml文件的寫入
import yaml
with open("result.yaml",'w',encoding = 'utf-8') as fp:
yaml.dump(yaml_data,fp,allow_unicode = True)
15.Python 3不再需要直接使用OrderedDict:
In [1]: {str(i):i for i in range(5)}
Out[1]: {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4}
16.使用_分割數字,更直觀。
In [1]: num = 100_000_000_000_000
In [2]: num
Out[2]: 100000000000000
In [3]: hex_num = 0x1234_ABCD
In [4]: hex_num
Out[4]: 305441741
In [5]: bin_num = 0b111_0011_0010
In [6]: bin_num
Out[6]: 1842
In [7]: f'{100000000000:_}'
Out[7]: '100_000_000_000'
17.獲取當前平臺信息。
In [1]: import platform
In [2]: platform.system()
Out[2]: 'Windows'
18.binascii模塊
binascii模塊包含很多在二進制和 ASCII 編碼的二進制表示之間的轉換方法。
In [1]: import binascii
In [2]: a = b'123456abc'
In [3]: b = binascii.hexlify(a)
In [4]: b
Out[4]: b'313233343536616263'
In [5]: binascii.a2b_hex(b)
Out[5]: b'123456abc'
JSON Python
版權聲明:本文內容由網絡用戶投稿,版權歸原作者所有,本站不擁有其著作權,亦不承擔相應法律責任。如果您發現本站中有涉嫌抄襲或描述失實的內容,請聯系我們jiasou666@gmail.com 處理,核實后本網站將在24小時內刪除侵權內容。
版權聲明:本文內容由網絡用戶投稿,版權歸原作者所有,本站不擁有其著作權,亦不承擔相應法律責任。如果您發現本站中有涉嫌抄襲或描述失實的內容,請聯系我們jiasou666@gmail.com 處理,核實后本網站將在24小時內刪除侵權內容。