python18-day6

 

内置函数

type    判断类型
name =("a","b")
print(type(name)) #看name类型  获取类
#<class 'tuple'>

bool(name)            0 空格,None都是False,其他都是True
name =("a","b")
print(bool(name))


len(name)               显示数据类型长度
name =("a","b")
print(len(name)) 

abs() #返回值为正数 print(abs(
-1)) #返回1 print(abs(2)) #返回2 print(abs(-0.1)) #返回0.1
all() #判断为True或False print(all([
1,2,3,4,5])) #值为True print(all([1,0])) #值为False, 值包含0,None,空都为False,其他都为True print(all([])) #值为True, 注意这是特殊情况,
二,八,十,十六进制
>>>bin(10) 二进制 '0b1010' >>> 10 十进制(默认) 10 >>> oct(10) 8进制 '0o12' >>> hex(10) 16进制 '0xa' a表示10 b表示11 以此类推
callable 可调用对象 #不是函数就不可被调用返回False def func(): pass print(callable(func)) #返回True
chr和ord ascii码是美国默认字符集编码 print(chr(
68)) #数字转换成ascii码 #D print(ord("D")) #ascii码转换数字 #68 dir 查看可用参数(权限) (有5种数据类型+set等) b={"1":"2"} print(dir(b)) divmod 用于分页功能 print(divmod(100,3)) #取整数+余数 (33, 1) print(divmod(100,3)[1]) #取余数 1

eval 把字符串里的命令或数据类型提取使用 #提取命令 cmd='print("三哥威武")' eval(cmd) #三哥威武 frozenset 定义不可变集合 s=frozenset({1,2}) #s=({1,2}) 这是可变集合 s.add(3) print(s) #会报错 因为s现在是不可变集合 format 字符串格式化 s="name:{},age:{},height:{}".format("guolm",23,"183") print(s) #name:guolm,age:23,height:183 hash 获取哈希,(2个字符串相同,哈希值相同) #效果:校验的内容相同 返回的值就一致 #以后会用hash模块,略过 print(hash("aaaaa")) print(hash("aaaaa")) -3564166969462102491 -3564166969462102491 id 取内存地址 name="aa"
print(id(name))
pow 求余数 print(pow(
10,2,6)) #4 #取余数 相当于10的2平方 除以6 得到的余数是4 reversed 取反转结果 a=["b","c","bd"] b=reversed(a) print(list(b)) #['bd', 'c', 'b'] round 保留小数 print(round(80.32341321,3)) #保留3位小数,四舍五入 #80.323 zip #两个相同长度的字符串,元组,列表组合成字典 #2个不同类型也可以组合 s=("hello") a=[1,2,3,4,5] z=zip(s,a) print(z) #<zip object at 0x0000004021D90608> z变成迭代器 print(list(z) #显示值 __import__() #以字符串的形式导入模块 import time import time m=__import__("time") m.sleep(3) #沉睡2秒 print("Gacvin Kwok is super man") sum 求和 a=sum([1,2,3,4]) #相当于1+2+3+4 print(a) 10 bytearray 字符串改值(在原内存空间更改.不是删除后增加) a="guolm 你好" print(ascii(a)) #ascii码 a=a.encode() #改成utf-8格式 b2=bytearray(a) #可直接修改字符串 b2[0]=98 #这是g(字节)改成b(字节) print(b2) #'guolm \u4f60\u597d' #bytearray(b'buolm \xe4\xbd\xa0\xe5\xa5\xbd')

 

re模块

re模块-正则
在线正则测试     http://tool.oschina.net/regex    

头疼去吧
print(re.findall(r"\-?\d+\.?\d*","1-12*(60+(-40.35/5)-(-4*2))"))         #匹配出所有数字
# #['1', '-12', '60', '-40.35', '5', '-4', '2']
print(re.findall(r"\-?\d+\.\d+|(\-?\d+)","1-12*(60+(-40.35/5)-(-4*2))")) #匹配所有整数
#|管道符左边是匹配所有小数,右边是匹配所有整数,()特性是先执行取结果,右边的执行匹配显示,左边匹配就抛弃
#['1', '-12', '60', '', '5', '-4', '2']



re.findall遍历匹配
#可以获取字符串中所有匹配的字符串,返回一个列表
import re
#如下匹配的字符串
 
转义成普通字符
print(re.findall(r"a[-\\n]c","abc a-c anc a_c a\c a\nc="))    #r开头是把所以变成普通字符 
#print(re.findall("a[-\\\\n]c","abc a-c anc a_c a\c a\nc="))  #也可用\\\\
#['a-c', 'anc', 'a\\c']
预定义字符集匹配
print(re.findall("a","abc\n121b3\ta_ef * | - ="))           #匹配所有a字符,a可变成任意字符或数字或空格符(\n或\t)
#['a', 'a']
print(re.findall("^a","abc\n121b3\t a_ef * | - =a"))        #^a匹配以a开头的 a$匹配以a结尾的
#['a']

print(re.findall("\w","abc123a_ef * | - ="))                #\w匹配字母数字下划线,不匹配特殊字符和空格
#['a', 'b', 'c', '1', '2', '3', 'a', '_', 'e', 'f']
print(re.findall("\W","abc123a_ef * | - ="))                #\W匹配非字母数字下划线,匹配特殊字符和空格
#[' ', '*', ' ', '|', ' ', '-', ' ', '=']
print(re.findall("\s","abc\n123\ta_ef * | - ="))            #\s匹配任意空白字符 等同于[\n\t\r\f]
#['\n', '\t', ' ', ' ', ' ', ' ']
print(re.findall("\S","abc\n123\ta_ef * | - ="))            #\S 匹配任意非空白字符
#['a', 'b', 'c', '1', '2', '3', 'a', '_', 'e', 'f', '*', '|', '-', '=']
print(re.findall("\d","abc\n123\ta_ef * | - ="))            #\d匹配任意数字0-9
#['1', '2', '3']
print(re.findall("\D","ta_ef- ="))                          #\D匹配非数字字符
#['t', 'a', '_', 'e', 'f', '-', ' ', '=']
print(re.findall(r'a\\c',"a\\c a\c a\\\\c"))          #r原生显示\\
#['a\\c', 'a\\c']

 
括号匹配
print(re.findall("com(?:aa|bb)","acomaavabbcombb ab a"))    #(aa|bb)匹配aa或bb com(?:aa|bb)匹配comaa和combb #如果不加?:匹配aa或bb
#['comaa', 'combb']

print(re.findall("a[-\n]c","abc a-ca_c a\tc a\nc="))        #[]匹配[]中包含的任意一个字符
#['a-c', 'a\nc']
 
print(re.findall('a[0-9][0-9]c','a a12c a1c a*c a2c a c a\nc',re.S)) #这是匹配2个条件
#['a12c']
print(re.findall("a[^-\n]c","abc a-c a c a_c a\tc a\nc="))   #[^]匹配[]中不包含的任意一个字符
#['abc', 'a c', 'a_c', 'a\tc']

print(re.findall("ab{2}","abvabb ab a"))                    #{}指定匹配abb  {2,5}匹配2-5次 {,5}匹配0-5次 {,5} 匹配5-n次
#['abb']
 
特殊符号匹配
^ 匹配开头 $匹配结尾 \转意字符
print(re.findall("comaa|combb","acomaavabbcombb ab a"))     # | comaa|combb 匹配comaa和combb
#['comaa', 'combb']

print(re.findall("a.c","abc a|c a c a_c a\tc a\nc="))       #"."匹配任意单个字符 不能匹配\n
#['abc', 'a|c', 'a c', 'a_c', 'a\tc']

print(re.findall("a.c","abc a|c a c a_c a\tc a\nc=",re.S))  #"."和re.s匹配任意单个字符且能匹配\n
#['abc', 'a|c', 'a c', 'a_c', 'a\tc', 'a\nc']
print(re.findall('a[^a-zA-Z]c','aac abc aAc a12c a1c a*c a2c a c a\nc',re.S)) #[^]匹配非[]内的数值
['a1c', 'a*c', 'a2c', 'a c', 'a\nc'] 

print(re.findall("ab*","a ab abb abbb"))                    # * 匹配0或n个前一个位的字符
#['a', 'ab', 'abb', 'abbb']

print(re.findall("ab+","a ab abb abbb"))                    # + 匹配1或n个前一个位的字符
#['ab', 'abb', 'abbb']

print(re.findall("ab?","a ab abb abbb"))                    #?匹配0或1个b
#['a', 'ab', 'ab', 'ab']
贪婪和非贪婪匹配
*?,+?,??,{m,n}?    前面的*,+,?等都是贪婪匹配,也就是尽可能匹配,后面加?号使其变成惰性匹配
print(re.findall("a.*c","aa123cabbbc"))                      #.* 贪婪匹配 匹配a开头c结尾
#['aa123cabbbc']
print(re.findall("a.*?c","aa123cabbbc"))                    #a.*?c 非贪婪匹配,匹配最短满足条件的
#['aa123c', 'abbbc']
a = re.findall(r"a(\d+?)",'a233b')    #非贪婪匹配
print(a)
b = re.findall(r"a(\d+)",'a233b')     #贪婪匹配
print(b)
执行结果:
['2']
['233']



 


complie()
#编辑正则表达式模式,返回一个对象的模式(可以把那些常用的正则表达式编译成正则表达式对象,这样可以提高一点效率。)
re.compile(pattern,flags=0)
re.compile(pattern,flags=0)
pattern: 编译时用的表达式字符串。
flags 编译标志位,用于修改正则表达式的匹配方式,如:是否区分大小写,多行匹配等。常用的flags有:
标志     
re.S(DOTALL)        #使.匹配包括换行在内的所有字符
re.I(IGNORECASE)  #使匹配对大小写不敏感
re.L(LOCALE)      #做本地化识别(locale-aware)匹配,法语等
re.M(MULTILINE)     #多行匹配,影响^和$
re.X(VERBOSE)       #该标志通过给予更灵活的格式以便将正则表达式写得更易于理解
re.U                #根据Unicode字符集解析字符,这个标志影响\w,\W,\b,\B



match object对象
re.match     只匹配字符串的开始,如果字符串开始不符合正则表达式,则匹配失败,函数返回None 
re.search   匹配整个字符串,直到找到一个匹配
#match和search一旦匹配成功,就是一个match object对象





a = "123abc456"
start() 返回匹配条件开始的位置
print(re.search("([0-9]*)([a-z]*)([0-9]*)",a).start())
#0
end() 返回匹配条件结束的位置
print(re.search("([0-9]*)([a-z]*)([0-9]*)",a).end())
#9
span() 返回一个元组包含匹配条件 (开始,结束) 的位置
print(re.search("([0-9]*)([a-z]*)([0-9]*)",a).span())   #(0,9)

group() 返回被 RE 匹配的字符串,()内输入数字可以一次输入多个分组,对应组号匹配的字符串

print(re.search("([0-9]*)([a-z]*)([0-9]*)",a).group(0))   #123abc456,返回整体
print(re.search("([0-9]*)([a-z]*)([0-9]*)",a).group(1))   #123
print(re.search("([0-9]*)([a-z]*)([0-9]*)",a).group(2))   #abc
print(re.search("([0-9]*)([a-z]*)([0-9]*)",a).group(3))   #456
#group(0) 列出所有匹配,         group(1) 列出第一个括号匹配部分,
#group(2) 列出第二个括号匹配部分,group(3) 列出第三个括号匹配部分。

re.split  切割 

分隔操作,分割后返回列表
print(re.split("[ba]","a2bcd")) #用b和a当分隔符
#['', '2', 'cd']
print(re.split('\d+','one1two2three3four4five5'))   #用数字当分割符
#['one', 'two', 'three', 'four', 'five', '']

re.sub 替换
print(re.sub("^g","G","guolm is man, guolm"))   #不加^ 匹配所有
#Guolm is man, guolm
print(re.sub("(\w+)(\s)(\w+)(\s)(\w+)",r"\5\2\3\4\1","alex make love"))
#位置替换 \w+匹配多个字母数字下划线,\s是空格  5-1是索引位置
#love make alex

print(re.sub("(\w+)(\W+)(\w+)(\W+)(\w+)",r"\5\2\3\4\1","alex ' \ + = make  ---/\ love")) #\W匹配非字母数字下划线
#love ' \ + = make  ---/\ alex


re.subn 替换,并返回次数

print(re.subn('[1-3]','A','12456ab13cdef'))  #包含1至3的数字替换成A 并显示替换次数
#('AA456abAAcdef', 4)
print(re.subn("g.t","have",'I get A,  I got B ,I gut C'))   #包含g.t 替换成have 并返回替换次数
#('I have A,  I have B ,I have C', 3)

finditer
搜索string,返回一个顺序访问每一个匹配结果(Match对象)的迭代器。找到 RE 匹配的所有子串,并把它们作为一个迭代器返回
iter = re.finditer(r'\d+','12 drumm44ers drumming, 11 ... 10 ...')
for i in iter:
    print(i)
    print(i.group())
    print(i.span())
# 12
# (0, 2)
# <_sre.SRE_Match object; span=(8, 10), match='44'>
# 44
# (8, 10)
# <_sre.SRE_Match object; span=(24, 26), match='11'>
# 11
# (24, 26)
# <_sre.SRE_Match object; span=(31, 33), match='10'>
# 10
# (31, 33)

time模块

import time
#
"%Y-%m-%d %H:%m:%S" 表示 年 月 日 时 分 秒  %X等于%H:%m:%S
print(time.time())                            #时间戳
#1496669778.464565
print(time.strftime("%Y-%m-%d %H:%m:%S"))     #显示数字时间

print(time.asctime())                         #返回时间日期 print(time.ctime())效果相同
#Mon Jun  5 21:29:37 2017

print(time.localtime())                       #显示本地结构化时间, print(time.localtime().tm_year) 可自定义显示
#time.struct_time(tm_year=2017, tm_mon=6, tm_mday=5, tm_hour=21, tm_min=33, tm_sec=8, tm_wday=0, tm_yday=156, tm_isdst=0)
print(time.gmtime())                          #显示utc(英国)时间结构化时间
#time.struct_time(tm_year=2017, tm_mon=6, tm_mday=5, tm_hour=13, tm_min=34, tm_sec=11, tm_wday=0, tm_yday=156, tm_isdst=0)

#时间戳转成数字时间 #struct_time
=time.localtime(time.time() - 86400 ) #减少86400秒(1天) #struct_time=time.localtime(14966778.0143368) #14966778.0143368是时间戳 struct_time=time.localtime(time.time()) #time.time是时间戳,time.localtime显示本地结构化时间,time.gmtime是显示utc(英国)时间 print(time.strftime("%Y-%m-%d %H:%M:%S",struct_time)) #time.strftime 将结构化时间显示成数字时间 #2017-06-05 22:07:13
#将数字时间显示成时间戳 string_time
=time.strptime("2016/05/22","%Y/%m/%d") #time.strptime将数字时间显示成结构化时间 struct_time=time.mktime((struct_time)) #time.mktime将结构化时间变成时间戳 print(struct_time) #14966778.0

random模块

import random
print(random.random())          #不能传参,随机生成大于0小于1之间的小数
#0.14251
print(random.uniform(1,3))      #随机生成大于1小于3的小数
#2.14251

print(random.randint(1,6))      #随机生成大于等于1且小于等于6的整数
#4
print(random.randrange(1,6))    #大于等于1且小于6的整数
#5

print(random.choice([1,'23',[4,5]]))  #随机得到1或23或[4,5]
#[4, 5]

print(random.sample([1,"23",[4,5]],2)) #随机获得任意2个元素,2可改
#[1, [4, 5]]

#随机更改itme元素顺序
item=[1,3,5,7,9]
random.shuffle(item)
print(item)
#[3, 5, 9, 7, 1]
#生成随机验证码
import random
def v_code():
    code = ''
    for i in range(5):
        num=random.randint(0,9)
        alf=chr(random.randint(65,90))
        add=random.choice([num,alf])
        code += str(add)
    return code
print(v_code())
#W3E01

os+sys模块

import platform
platform.platfrom()                #显示系统版本
platform.system()                  #显示系统版本
os.chdir("/home")                  #切换到/home目录模块
os.getcwd()                        #获取当前目录
os.system("ls -h")                 #在python中执行shell命令(不能切换目录),
d=os.popen("df -h").read()         #把df的执行结果赋值给d  #os.popen("df -h").read() 执行命令
print(d)

 删除文件
import os,sys
file_path=os.path.abspath(__file__)        #本文件绝对路径
file_1=os.path.dirname(file_path)          #本文件目录路径
f=file_1+"/file_tow.log"                   #加/file_tow.log
os.remove(f)                               #删除/file_tow.log

 
 

os.path.abspath(__file__)                           #os.path.abspath 返回文件绝对路径
os.mkdir("guol11")                                  #创建1个目录
os.makedirs("/home/guolm/1112211/a2/a3")            #创建多层目录
os.makedirs("/home/guolm/1112211aa",exist_ok=True)  #创建文件存在,就覆盖 不会报错
os.rmkdir("guol11")                                 #目录为空,则删除,否则报错
os.removedirs("1112211/a2/a4/")                     #可写绝对路径,若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推
os.listdir("")            #列出当前目录所有,包含隐藏文件 os.listdir("..")列出上层目录所有
os.rename("guo","gg")     #重命名 guo为gg
os.stat("gg")             #获取文件或目录信息  os.stat("gg").st_size 获取文件大小 (看输出写参数)
os.sep                    #显示分割符,win下为"\\",Linux下为"/"
os.linesep                #输出行终止符,win下为"\r\n",Linux下为"\n"
os.pathsep                #分割文件路径的字符 win是; linux是:
os.environ                #获取系统的环境变量
   
返回文件路径
import os,sys
file_path=os.path.abspath(__file__)                 #os.path.abspath 返回文件绝对路径
print(file_path)
#E:\install\pycharm\guolm\day6\supba.py

print(os.path.dirname(file_path))                   #返回文件的目录路径
#E:\install\pycharm\guolm\day6

print(os.path.dirname(os.path.dirname(file_path)))  #返回文件的目录上层目录的路径
E:\install\pycharm\guolm
 
print(os.path.basename(file_path))                  #返回文件名
supba.py

 
print(os.path.split(file_path))                     #优化返回文件的目录绝对路径
#('E:\\install\\pycharm\\guolm\\day6', 'supba.py')

print(os.path.exists(file_path))        #判断文件路径是否存在 True为真 False为假
#True
print(os.path.isabs(file_path))         #判断文件是否为绝对路径,True为真 False为假
#True
print(os.path.isfile(file_path))        #判断file_path是否为存在的文件
#True
print(os.path.isdir(file_path))         #判断file_path是否为存在的目录
#False
print(os.path.getatime(file_path))      #返回file_path文件或目录最后存取时间
#1496854045.527072
print(os.path.getatime(file_path))      #返回file_path文件或目录最后修改时间
#1496854045.527072
sys模块

import sys
print(sys.path)         #返回模块路径
print(sys.version)      #输出python版本信息
print(sys.maxsize)      #输出最大的int值
print(sys.platform)     #显示系统类型


sys.argv                #把sys.argv写模块 被调用会显示绝对路径,后边跟的值也是传参给列表                  
test2.py 文件名
import sys
sys.argv
print(sys.argv)

#cd 到test2.py目录执行如下
python3.6 test2.py a b c    # a b c 是参数
['test2.py', 'a', 'b', 'c'] #把目录和参数合成为列表
使用sys.agv 调用位置参数  进行copy
import sys 
 
#python3 copy.py source.file target.file
if len(sys.argv) < 3:
    print('Usage:python3 copy.py source.file target.file')
    sys.exit()
with open(r'%s' %sys.argv[1],'rb') as read_f,\
        open(r'%s' %sys.argv[2],'wb') as write_f:
    for line in read_f:
        write_f.write(line) 
 
在命令行执行,先cd 好day.py文件的目录
python3.6 day3.py f1.log f2.log        #day.py是如上程序 f1.log是内容 复制到f2.log
文件写入就显示
#执行方法  python3 tail.py -f access.log
import time
import sys
with open(r'%s' %sys.argv[2],'rb') as f:
    f.seek(0,2)
    while True:
        line=f.readline()
        if line:
            print(line)
        else:
            time.sleep(0.2)

 

#交互,用户可输入1行内容
# a=sys.stdin.readline()
# print(a)

m=sys.modules[__name__]    #获取当前模块名
print(m)

 

posted @ 2017-08-09 11:35  Gavinkwok  阅读(199)  评论(0编辑  收藏  举报