python常用函數(shù)

1.?os.path.split(file_path)

只會(huì)識別file_path最后一個(gè)‘/’,并以此切割,生成一個(gè)列表

例如:

>json_file = "/opt/data/json_file/example.json"

>os.path.split(json_file)

得到 ('/opt/data/json_file', 'example.json')

2. os.walk(path)

遍歷path下所有的目錄和文件

例如:

>path = '/data1/data/'

>for root,dirs,files in os.walk(path):

? ? print('root:{}'.format(root))

? ? print('dirs:{}'.format(dirs))

? ? ?print('files:{}'.format(files))

得到

root:/data1/data/? #第一個(gè)root為輸入path的完整路徑

dirs:['hello', 'hello1'] #在第一個(gè)完整路徑下,存在hello和hello1兩個(gè)目錄也就是文件夾

files:['hello.py', '123.txt']#在第一個(gè)完整路徑下有兩個(gè)文件

root:/data1/data/hello #第二個(gè)root為hello的完整路徑

dirs:[] #在hello路徑下沒有目錄

files:['a.txt'] #在hello路徑下,存在一個(gè)a.txt文件

root:/data1/data/hello1 #第三個(gè)root為hello1的完整路徑

dirs:[] #在hello1下沒有目錄

files:[] #在hello1下也沒有文件

3. os.walk 和?os.path.splitext 及os.path.join

功能:將給定目錄及子目錄下符合要求的文件都放到列表中
>final_path_list = []

>pcap_dir = '/data1/data/'

>for parent, dirnames, filenames in os.walk(pcap_dir, followlinks=True):

? ? print('parent:{}'.format(parent))

? ? print('dirnames:{}'.format(dirnames))

? ? print('filenames:{}'.format(filenames))

? ? for filename in filenames:

? ? ? ? print('filename:{}'.format(filename))

? ? ? ? if os.path.splitext(filename)[1] == '.cap' or os.path.splitext(filename)[1] == '.pcap':

? ? ? ? ? ? file_path = os.path.join(parent, filename)

? ? ? ? ? ? final_path_list.append(file_path) #得到所有文件的絕對路徑

得到

parent:/data1/data/

dirnames:['hello', 'hello1']

filenames:['hello.py', '123.pcap']

filename:hello.py

filename:123.pcap

parent:/data1/data/hello

dirnames:[]

filenames:['a.txt', '1.pcap', '2.pcap']

filename:a.txt

filename:1.pcap

filename:2.pcap

parent:/data1/data/hello1

dirnames:[]

filenames:['3.pcap', '4.pcap']

filename:3.pcap

filename:4.pcap

>?final_path_list

得到

['/data1/data/123.pcap',

'/data1/data/hello/1.pcap',

'/data1/data/hello/2.pcap',

'/data1/data/hello1/3.pcap',

'/data1/data/hello1/4.pcap']

4. 將json文件以標(biāo)準(zhǔn)DataFrame方式輸出

例如:

>primal_json = {'File_name':[],'srcIP':[],'dstIP':[]}

>primal_json['File_name'].append('A')

>primal_json['srcIP'].append('10.1.2.32')

>primal_json['dstIP'].append('132.21.32.12')

>df_primal = pd.DataFrame(primal_json)

>df_primal


pig:df_primal

5. 將字典鍵值對中的鍵變?yōu)樾?,且如果有下劃線“_”,替換為“-”

>new_header_dict = {}

>for k, v in header.items():

? ? new_header_dict[k.lower().replace('_','-')] = v

6. 字典的寫入和讀取

1) 將字典寫入txt文件

>import json

>dict = {"Alice":97,"Bob":98,'300':{'sig':['abc'],'file':'1.txt'},'family':'UK'}

>json_str = json.dumps(dict) #dumps

>with open('/data/test_dict.txt', 'w') as f:

? ? >f.write(json_str)

打開txt文件顯示

{"Alice": 97, "Bob": 98, "300": {"sig": ["abc"], "file": "1.txt"}, "family": "UK"}

2)將txt文件中的字典讀出來

>json_file = "/data/test_data.txt"

>with open(json_file,'r')as f:

? ? >json_lines = f.read()

? ? >dic = json.loads(json_lines) #json.loads()是用來讀取字符串

>dic

顯示

{'300': {'file': '1.txt', 'sig': ['abc']},

'Alice': 97,

'Bob': 98,

'family': 'UK'}

或者

>with open("/data/test_data.txt",'r')as f:

? ? >sig = json.load(f)? # json.load()是用來讀取字典文件

同樣顯示

{'300': {'file': '1.txt', 'sig': ['abc']},

'Alice': 97,

'Bob': 98,

'family': 'UK'}

7.針對dataframe想使得一列是空列表

例如:

>data={"one":np.random.randn(4),"two":np.linspace(1,4,4),"three":['zhangsan','李四',999,0.1]}

>df=pd.DataFrame(data,index=[1,2,3,4])

得到


pig: df

想在df的后面一列添加空列表(每一行都是空列表)


pig: df_null

需要如下操作:

>df['null_list'] = [[] for _ in range(len(df))]

其實(shí)df['null_list']的賦值可以是列表如[1,2,3,4]

這里需要變成[[],[],[],[]]

8.?maxsplit=1的使用

maxsplit = 1將字符串從第一個(gè)空格切開,生成空格前和空格后兩部分子串

例如:

>'1,2,3'.split(',')

得到?['1', '2', '3']

>'1 2 3'.split(maxsplit=1)

得到?['1', '2 3']

9. str.isdigit()

檢查字符串是否只由數(shù)字組成

例如:

>str = "123456"

>print(str.isdigit())

得到? True

>str = '123hello'

>print(str.isdigit())

得到? False

10. eval函數(shù)

用來執(zhí)行一個(gè)字符串表達(dá)式,并返回表達(dá)式的值

首先輸入是字符串

例如:

>x = 7

> eval( '3 * x' )

得到? 21

再例如:

>df['Request-Header-Dict'].iloc[0]

"{'host': 'bublikiadministrator.com', 'user-agent': '_', 'method': 'GET', 'path': '/?&v=old_load&s=2433', 'http-version': 'HTTP/1.1'}" #注意是字符串

>df['Request-Header-Dict'] = df['Request-Header-Dict'].map(eval)

得到?

{'host': 'bublikiadministrator.com',

'http-version': 'HTTP/1.1',

'method': 'GET',

'path': '/?&v=old_load&s=2433',

'user-agent': '_'} # 變成真實(shí)的字典了

可以認(rèn)為eval函數(shù)是去除字符串含義,變?yōu)檎鎸?shí)的表達(dá)含義

11. setdefault函數(shù)

字典 setdefault() 函數(shù)和?get()方法?類似, 如果鍵不存在于字典中,將會(huì)添加鍵并將值設(shè)為默認(rèn)值,如果字典中包含有給定鍵,則返回該鍵對應(yīng)的值,否則返回為該鍵設(shè)置的值。

>dict = {'runoob': '菜鳥教程', 'google': 'Google 搜索'}

>print('value:{}'.format(dict.setdefault('runnoob',None)))

得到??value:None

>print('value:{}'.format(dict.setdefault('runoob',None)))

得到??value:菜鳥教程

>print('value:{}'.format(dict.setdefault('google','GOOGLE')))

得到??value:Google 搜索

12.?urllib.parse.urlparse解析url

例如:

> import urllib.parse

>?url = 'http://bublikiadministrator.com/?&v=old_load&s=2433'

>parse_url = urllib.parse.urlparse(url)

>parse_url

得到:ParseResult(scheme='http', netloc='bublikiadministrator.com', path='/', params='', query='&v=old_load&s=2433', fragment='')

>url_host = parse_url.netloc

>url_host

得到:'bublikiadministrator.com'

>url_query = parse_url.query

>url_query

得到:?'&v=old_load&s=2433'

想獲得url里的請求參數(shù)和值

>lst_url_query_keys = urllib.parse.parse_qsl(parse_url.query)? #以列表形式輸出

>lst_url_query_keys?

得到:[('v', 'old_load'), ('s', '2433')]

>dict_url_query_keys = urllib.parse.parse_qs(parse_url.query) #以字典形式輸出

>dict_url_query_keys?

得到:{'s': ['2433'], 'v': ['old_load']}

13. AI模型的fit()、transform()及fit_transform()

Fit():Method calculates the parameters μ and σ and saves them as internal objects.

Transform():Method using these calculated parameters apply the transformation to a particular dataset.

Fit_transform():joins the fit() and transform() method for transformation of dataset.

注意:必須先fit再transform? 而fit_transform等同于 先fit再transform

例如:

>import pandas as pd

>import numpy as np

>from sklearn.decomposition import PCA

>x1 = pd.DataFrame(np.arange(9).reshape((3,3)),index=['a','b','c'],columns=['one','two','three'])

>x1

pig: x1

>pca = PCA(n_components=1)

>m1 = pca.fit(x1)

>newx1 = m1.transform(x1)

>newx1

得到:array([[ 5.19615242],

? ? ? [ 0.? ? ? ? ],

? ? ? [-5.19615242]])

>newx1_1 = pca.fit_transform(x1)

>newx1_1

得到:array([[ 5.19615242],

? ? ? [-0.? ? ? ? ],

? ? ? [-5.19615242]])

結(jié)果是一樣的

而如果使用x1數(shù)據(jù)來訓(xùn)練模型,用于測試其他數(shù)據(jù),則使用m1.transform即可

>a=[[1,2,3],[5,6,7],[4,5,8]]

>x2 = x2=pd.DataFrame(np.array(a),index=['a','b','c'], columns=['one','two','three'])?

>x2

pig:x2


>newx2_ = pca.fit_transform(x2)

>newx2_

得到:

array([[ 4.45942145],

? ? ? [-2.42594197],

? ? ? [-2.03347948]])

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容