python常用函数

1. os.path.split(file_path)

只会识别file_path最后一个‘/’,并以此切割,生成一个列表

例如:

>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/  #第一个root为输入path的完整路径

dirs:['hello', 'hello1'] #在第一个完整路径下,存在hello和hello1两个目录也就是文件夹

files:['hello.py', '123.txt']#在第一个完整路径下有两个文件

root:/data1/data/hello #第二个root为hello的完整路径

dirs:[] #在hello路径下没有目录

files:['a.txt'] #在hello路径下,存在一个a.txt文件

root:/data1/data/hello1 #第三个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文件以标准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. 将字典键值对中的键变为小写,且如果有下划线“_”,替换为“-”

>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))]

其实df['null_list']的赋值可以是列表如[1,2,3,4]

这里需要变成[[],[],[],[]]

8. maxsplit=1的使用

maxsplit = 1将字符串从第一个空格切开,生成空格前和空格后两部分子串

例如:

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

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

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

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

9. str.isdigit()

检查字符串是否只由数字组成

例如:

>str = "123456"

>print(str.isdigit())

得到  True

>str = '123hello'

>print(str.isdigit())

得到  False

10. eval函数

用来执行一个字符串表达式,并返回表达式的值

首先输入是字符串

例如:

>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': '_'} # 变成真实的字典了

可以认为eval函数是去除字符串含义,变为真实的表达含义

11. setdefault函数

字典 setdefault() 函数和 get()方法 类似, 如果键不存在于字典中,将会添加键并将值设为默认值,如果字典中包含有给定键,则返回该键对应的值,否则返回为该键设置的值。

>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里的请求参数和值

>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]])

结果是一样的

而如果使用x1数据来训练模型,用于测试其他数据,则使用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]])

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,039评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,426评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,417评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,868评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,892评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,692评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,416评论 3 419
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,326评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,782评论 1 316
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,957评论 3 337
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,102评论 1 350
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,790评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,442评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,996评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,113评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,332评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,044评论 2 355

推荐阅读更多精彩内容