首页 > 编程语言 >python入门学习之《python编程快速上手》

python入门学习之《python编程快速上手》

时间:2023-06-16 20:23:56浏览次数:48  
标签:入门 spam python mo 编程 列表 字符串 print name

#《python编程快速上手》1-9章

第1-2章:python基础和控制流

#python严格区分大小写;
#代码行的缩进很重要,一般用4个空格。大多数情况下,代码行缩进告诉python它属于哪个代码块。
#python下标从0开始;
#行末使用续行字符\,将一行指令写成多行。在 [], {}, 或 () 中的多行语句,不需要使用反斜杠(\)
#字符串''是不可变数据类型;列表[]是可变数据类型,元祖()是列表的不可变形式
#input()函数:等待用户输入内容并按下回车键
##'''...#''',"...":3个引号表示块注释
#!=表示不等于、==表示等于;=表示变量赋值
#模块导入的两种写法:import 模块 | from 模块 import *;两种写法的区别是第二种调用函数时不需要模块前缀


# return 和 print的区别:
# 在执行函数的时候return无法打印值,return返回的结果只能用于给变量赋值;pirnt则可以直接打印值。
# return还有一个重要特性:在函数中,凡是遇到return,这个函数就会结束,这里要特别注意。\
# 针对无限循环的函数,可以使用return

# 数据类型
#python常用的数据类型有:整型(int)、浮点型(Float)、字符串(string)
#方法和函数是一回事,只是函数是调用在一个值上,且每种数据类型都有自己的一组方法

##############################################
# 重点1:if控制流说明:
# 1如果 if语句的子句:只有在条件为True时执行,否则跳过;
# 2否则 else语句:跟在if后,只有if语句的条件为False时,else语句才执行
# 3否则如果 elif语句:总是跟在if或另一条elif语句后面。
# elif语句仅在前面条件都为False时才检查该条件,该条件为True时执行;多个elif为True时,只执行第一条为True的条件,剩下的elif自动跳过,所以elif语句次序很重要;
# 在最后1个elif语句后面加上else语句,可以保证至少执行一个(且只有一个)子句
#此时,如果每个if和elif中的条件为False,就执行else语句

#if语句:只有在条件为True时执行,否则跳过;

print('please input your name')
name=input()
if name == 'a': #冒号不要忘记
    print('hi,a') #子句一定要缩进

#if.else语句:跟在if后,只有if语句的条件为False时,else语句才执行

print('please input your name')
name=input()
if name == 'a': #冒号不要忘记
    print('hi,a')
if name =='b':
        print('hi,b')
else: #冒号不要忘记
        print('omg,hi,'+name)

#elif语句:总是跟在if或另一条elif语句后面,仅在前面的条件为False时才执行

print('please input your name')
name=input()
if name == 'a':
    print('hi,a')
elif name=='b':
        print('hi,b')
elif name=='c':
        print('hi,c')
#else:
#        print('you win')

#while 循环
 #while条件为True时执行子句,执行完毕后程序执行跳回到while语句开始处;
 #当while条件第一次为False时,就会跳出while子句循环

a=0
while  a<5:
        print('hello,word')
        a=a+1

#break语句:当条件为True时跳出while循环

while True:
    print('please input your name:')
    name=input()
    if name=='alice':
        break
print('bye,bye')

#continue语句:遇到coninue,程序跳回循环开始处

while True:
        print('please input your name:')
        name=input()
        if name=='alic':
                continue
        if name=='alice':
                break
        print('bye,bye')

#for循环
#语法:range(起始值,终止值(不包含它),步长(默认1))
#range(5)表示:变量从0默认按步长1递增到5(但不包括5)

#计数1到100求和
total=0
for i in range(101):
    total=total+i
print(total)

#导入模块imoport
#random.randint()函数调用求值为传递给它的两个整数之间的一个随机整数,如1-10之间随机给5个数

import random
for i in range(5):
    print(random.randint(1,10))

#用sys.exit()提前结束程序

#写法1
import sys
while True:
        print('please input end to exit:')
        response=input()
        if response=='exit':
                sys.exit()


#写法2
from sys import *
while True:
        print('please input end to exit:')
        response=input()
        if response=='exit':
                exit()

 

第3章:函数

#def和参数

#def语句定义了一个hello函数,name是一个变元,保存在变元中的值,在函数返回后就丢失了
#创建函数
def hello(name):
    print('hello '+name)
    return #返回值为None
#调用printme函数
pyy='pengyuanyuan'
hello(pyy) #实际调用时一般传入的是内容或者任意变量名,不一定命名为name

#返回值和return语句
#用def创建函数时,可以用return指定返回什么值
#如果函数没有return语句(或者只有return本身),其返回值为None

import random
def getanswer(answer):
    if answer==1:
        return 'it is 1'
    elif answer==2:
        return 'it is 2'
    elif answer==3:
        return 'it is 3'
r=random.randint(1,3)
R=getanswer(r)
print(R)

#无参函数就是参数列表为空的函数

#如果函数在调用时不需要向函数内部传递参数,就可以使用无参函数。
def num():
    print('Hello Python')
#函数中保存的代码不会立即执行,需要调用函数代码才会执行
num()#调用函数

 

def spam(devide):
    return 42/devide
print(spam(2))
print(spam(12))
print(spam(1))

 

#异常处理:try和except语句
#将可能出错的语句放在try子句中,如果错误发生,程序就转到except语句。except语句执行完后,向下执行

def spam(devide):
    try:
        return 42/devide
    except:
        print('error')
print(spam(2))
print(spam(12))
print(spam(0))
print(spam(1)) 

#注意和上面区别
#区别在于:下式print(spam(1))未被执行,将spam放到语句块中,一旦跳到except语句就不会再回到try语句
def spam(devide):
    return 42/devide

try:
    print(spam(2))
    print(spam(12))
    print(spam(0))
    print(spam(1))
except:
    print('error')

 

 

#练习:猜数字小程序
print('this is a guess the number game')
import random
secnum=random.randint(1,20)
print('i am thinking of a number between 1 and 20')

#ask player to guess 6 times
for guesstime in range(1,7):
        print('take a guess')
        guess=int(input())

        if guess<secnum:
                print('your guess is too low')
        elif guess>secnum:
                print('your guess is too high')
        else:
                break
if guess==secnum:
        print('good job! youguessed my number in '+str(guesstime)+' guesses!')
else:
        print('no,the number i was thinking of was '+str(secnum))


#3.11.1练习:有问题
def collatz(number):
    try:
        if number%2==0:
            print(number)
        elif number%2==1:
            print(3*number+1)
    except:
        print('you must input number')
                

while True:
    print('input a number')
    num=input()
    if collatz(num)!=1:
        print('input a number')
        num=input()

    else:
        break
if collatz(num)==1:
    collatz(num)

 

第4章 列表和元祖

#列表看起来像['a','b','c','d'],只能是字符串或者数字
cat=['fat','black','loud']
cat[0] #获取第一个值,第一个值的下标从0开始
cat[-1] #负数下标,-1指列表中最后一个下标,以此类推
cat[1:3] #切片下标
cat[:3] #省略第1个下标相当于使用0
cat[3:] #省略第2个下标相当于使用列表的长度,切片直至列表末尾
len(cat) #获取列表长度
cat[1]='bat' #使用下标改变列表中的值
cat

del cat[0] #del语句删除列表中下标处的值

# +操作符连接两个列表
a=['a','b','c','d']+['fat','black','loud']
# *操作符用于一个列表和一个整数,实现列表复制
a=['a','b','c','d']*3

#多重下标访问
cat=[['fat','black','loud'],[10,20,30,40]]
cat[0][1] #black

#在for循环中迭代列表的每一个下标

#在for循环中迭代列表的每一个下标 range(len(list))
supplies=['a','b','c','d']
for i in range(len(supplies)):
    print('index '+str(i))

#in和not in:确定一个值是否在列表中,返回布尔值
supplies=['a','b','c','d']
'a' in supplies
'e' not in supplies


#多重赋值:用列表的值为多个变量赋值;注意:变量的数目和列表的长度严格相等
cat=['fat','black','loud']
size,color,disposition=cat

#增强赋值操作:适用于对变量赋值时用到变量本身
#增强的赋值语句 等价的赋值语句
spam+=3 spam=spam+3
spam-=3 spam=spam-3
spam*=3 spam=spam*3
spam/=3 spam=spam/3
spam%=3 spam=spam%3

a=['love']
a*=3 #重复3次
print(a)

#方法:和函数是一回事,只是函数是调用在一个值上。
# 每种数据类型都有自己的一组方法
#index()方法在列表中查找值,返回第一次出现的下标
cat=['fat','black','loud']
a=cat.index('loud')
print(a) #返回2

#用append()和insert()方法在列表中添加值
#append() 将参数添加值列表末尾
cat=['fat','black','loud']
cat.append('loud')
print(cat)

#insert()可在列表任意下标处插入一个新值:第一个参数是新值的下标,第二个参数是要插入的新值
cat=['fat','black','loud']
cat.insert(0,'loud')
print(cat)

#remove()方法删除第一次出现的值
cat=['fat','black','loud']
cat.remove('fat')
print(cat)

#sort()方法对列表中的数值或者字符串排序;不能对既有字符串又有数字的列表排序
a=[10,20,30,40] #数值排序
a.sort()
print(a)

a=['a', 'b', 'c', 'd', 'black', 'loud']
a.sort() #sort方法对字符串使用ASCII字符排序,非字典顺序排序
a.sort(key=str.lower,reverse=True) #指定按照普通字典顺序排序,逆序排序reverse=True
print(a)

#对列表的许多操作也可以作用于字符串:比如按下标取值、切片、用于for循环、用于len()以及in、not in等操作
name='Zophie'
name[0]
name[:4]
'z' in name
for i in name:
print('****'+i+'****')


#可变数据类型:指其值可以直接修改、删除和添加;不可变数据类型则相反
#字符串是不可变数据类型'',改变字符串的正确方式是使用切片和连接构造新的变量
#列表是可变数据类型[],元祖是列表数据类型的不可变形式,是不可改变数据类型
name=[1,2,3]
name[1]=10 #直接修改
print(name) #返回[1, 10, 3]

#元组():使用(),而不是[]
egg=('a', 'b', 'c', 'd', 12, 13.0) #元组可以可以包含多种类型的数据
type(('hello',)) #只有一个值时最后加个逗号表明是元组
type(('hello'))

#list函数和tuple函数来转换类型
#列表转换成元组
inf=['a', 'b', 'c', 'd', 12, 13.0]
tuple(inf)
#元组转换成列表
inf2=('a', 'b', 'c', 'd', 12, 13.0)
list(inf2)

#字符串转换成列表
list('abcd') #返回['a', 'b', 'c', 'd']

#引用与变量赋值的区别
#在变量必须保持可变数据类型的值时,如列表或字典,python就引用;
#对于不可变的数据类型,如字符串、整型或元祖,python就保存变量本身

#变量赋值:spam和chees是不同的变量保存了不同的值
spam=42
chees=spam
spam=100
spam
chees

#引用:spam和chees指向同一个列表
spam=[0,1,2,3,4,5] #当将列表赋值给变量时,实际上是列表的“引用”赋给了该变量
chees=spam
chees[1]='hello!'
spam
chees

#复制列表或字典:copy模块的copy函数和deepcop()函数?
#如果需要对一个变量中的列表修改,同时不修改原来的列表,使用copy函数和deepcop()函数
#spam和chees指向独立列表
import copy
spam=['a', 'b', 'c', 'd']
chees=copy.copy(spam)
chees[1]=42
spam
chees


#理解参数如何传递给函数,引用就特别重要
#传递引用:当函数被调用时,参数的值会复制给变元,意味着变元得到的是引用的拷贝
def eggs(someparameter):
someparameter.append('hello')

spam=[1,2,3]
eggs(spam) #尽管someparameter和spam是两个变量,但他们都指向相同的列表
print(spam) #这就是append('hello')方法调用在函数返回后仍然对该列表产生影响的原因

#练习:逗号代码
 #编写一个通用的函数,以一个列表之作为参数,返回某种格式字符串
 #写法1
def comma(spam):
    newspam = ''
    for i in range(len(spam) - 1):
        newspam = newspam + spam[i] + ', '
    newspam = newspam + 'and '+ spam[-1]
    return newspam

spam = ['apples', 'bananas', 'tofu', 'cats']
print(comma(spam)) #返回 'apples, bananas, tofu, and cats'

 

第5章 字典和结构化数据

#字典:字典输入时带花括号{},字典的索引称为“键”,键及其关联值称为“键-值”对,因为字典不排序所以顺序不重要
#字典可以用各种数据类型作为键:整型、浮点型、字符串、元祖
#字典和列表的区别:字典当中的元素是通过键来存取的,而不是通过偏移存取;字典可以和列表和元组嵌套

#keys()、values()、items()方法
#3个字典方法返回类似列表的值:
# keys()对应字典的键
# values() 对应字典的值
# items() 对应字典的键值对
#但这3个方法返回的不是真正的列表,它们不能被修改,没有append()方法
#如果希望得到一个真正的列表,就把类似列表的返回值传递给list()函数
#但这些数据类型可以用于for循环(dict_keys、dict_values、dict_items)

spam={'color':'red','age':'42'}
for a in spam.values():
    print(a)
    
print(list(spam.values())) #得到字典的值的列表

for b in spam.keys():
    print(b)
    
print(list(spam.keys())) #得到字典的键的列表

for c in spam.items():
    print(c) #返回的是包含键和值的元组
    
print(list(spam.items())) #得到字典的键值对的列表

#可以利用多重赋值的技巧,在for循环中将键和值赋给不同的变量

spam={'color':'red','age':'42'}
for k,v in spam.items():
    print(' key: '+ k +' value: '+str(v))

 

#检查字典中是否存在键或值

#in 和not in
spam={'name':'Zophie','age':7}
'name' in spam.keys()
'name' in spam.values()
'name' in spam.items()
'name' in spam #用in或not in作用于字典本身,检查一个值是否为字典的键

#get()方法:如果键存在则返回该键的值,否则返回备用值;但是没有改变原对象的数据
spam={'name':'Zophie','age':7}
spam.get('age',0)

#setdefault()方法:第一个参数为要检查的键
#若该键存在,则返回键的值;若该键不存在,则将默认值赋给该键,并返回默认值
spam={'name':'Zophie','age':7}
spam.setdefault('color','black') #值black赋给color键,并返回black
spam.setdefault('color','white') #返回black,此时color键已经存在

 

##字典常用操作

D1={} #空字典
D1={'one':1} #字典直接增加数据。列表只能通过append方法,即list[1]='A'方式修改序列数据
# dict[key]=value #增加数据:已经存在就是修改,没有存在就是增加数据
D1['catgory']='class'

D2={'name':'diege','age':18} #两项目字典

list(D2) #获取D这个字典的KEY的并按字典顺序排序成一个列表(真正的列表)
D2['name'] #通过键访问值
D2.keys() #返回键列表(不是真正的列表)
D2.values() #返回值列表
D2.items() #返回字典键值对的列表
D2.get(key,deault) #默认如果key存在就返回key的value,如果不存在就设置key的value为default。未改变原对象的数据
D2.copy() #方法:拷贝
D2.update(D1) #方法:合并。D1合并到D2,D1没有变化,D2变化。注意和字符串,列表的合并操作”+“不同
D2.pop('age') #方法:删除 根据key删除,并返回删除的value
D2.clear() #清空字典所有数据
len(D2) #方法:求长(存储元素的数目)
'name' in D2 #方法:成员测试:注意使用key来测试

D3={'name':{'first':'diege','last':'wang'},'age':18} #字典嵌套字典
D3['name']['last'] #字典嵌套字典的键索引

D4={'one':[1,11,111],'two':[2,22,222]}
D4['two'][0] #字典嵌套列表的键索引

D5={'one':(1,11,111),'two':(2,22,222)}
D5['one'][2] #字典嵌套元组的键索引

D6=dict(name='diege',age=18) #其他构造技术
D7=dict.fromkeys(['a','b']) #其他构造技术 dict.fromkeys 可以从一个列表读取字典的key 值默认为空,可指定初始值.两个参数一个是KEY列表,一个初始值

 

#练习1:保存朋友的生日数据,使用一个字典,用名字作为键,用生日作为值。如果名字不在就添加进去

#练习1:保存朋友的生日数据,使用一个字典,用名字作为键,用生日作为值。如果名字不在就添加进去
birthdays ={'Alice':'Apr 1','Bob':'Dec 12','Carol':'Mar 4'}
while True:
    print('Enter a name:(black to quit)')
    name = input()
    if name == '':
        break
    if name in birthdays:
        print(birthdays[name]+' is the birthday of '+name)
    else:
        print('I do not have birthday information for '+ name)
        print('what is their birthday?')
        bday = input()
        birthdays.setdefault(name,bday)
        print('birthday database updated.')

 

#练习2:计算一个字符串中每个字符出现的次数

#练习2:计算一个字符串中每个字符出现的次数
 #写法1直接输出
message='It was a bright cold day in April,and clocks were striking thirteen'
count={} #字典格式
for character in message:
    count.setdefault(character,0) #避免抛出KeyError
    count[character]=count[character] + 1

print(count)

 #写法2:导入pprint模块实现漂亮打印:使用pprint函数和pformat函数
import pprint
message='It was a bright cold day in April,and clocks were striking thirteen'
count={}
for character in message:
    count.setdefault(character,0)
    count[character]=count[character] + 1

pprint.pprint(count) #返回类型:<class 'NoneType'>,不能再传递
print(pprint.pformat(count))  #两种写法结果一样

#练习3:计算所有客人带来的食物的总数

#练习3:计算所有客人带来的食物的总数
 #字典内嵌套字典
allGuests = {'Alice':{'apples':5,'pretzels':12},\
             'Bob'  :{'ham sandwiches':3, 'apples':2},\
             'Carol':{'cups':3,'apple pies':1}}
    

def totalBrought(guests,item):
    numBrought = 0
    for k,v in guests.items():
        numBrought = numBrought + v.get(item,0)

    return numBrought

  #如何最外层的水果键取出来去重,而不是写死呢?如何取出键值对中值里面的键?
lst=('apples','pretzels','cups','cakes','ham sandwiches','apple pies')


for fruit in lst:
    print(' - '+fruit +'  '+str(totalBrought(allGuests,fruit)))
    
 #for循环执行结果等价于下面这一段
print(' - Apples '+str(totalBrought(allGuests,'apples')))
print(' - pretzels '+str(totalBrought(allGuests,'pretzels')))
print(' - cups '+str(totalBrought(allGuests,'cups')))
print(' - cakes '+str(totalBrought(allGuests,'cakes')))
print(' - ham sandwiches '+str(totalBrought(allGuests,'ham sandwiches')))
print(' - apple pies '+str(totalBrought(allGuests,'apple pies')))

  #如何最外层的水果键取出来去重,而不是写死呢?如何取出键值对中值里面的键?下一步怎么合并呢?
for k,v in allGuests.items():
         print(v.keys())
  #返回结果如下,下一步怎么合并呢?
dict_keys(['apples', 'pretzels'])
dict_keys(['ham sandwiches', 'apples'])
dict_keys(['cups', 'apple pies'])    

 

#练习4:好玩的游戏物品清单

 #计算玩家有多少种物品
 #使用for循环遍历字典中的所有键
game_item = {'rope':1,'torch':6,'glod coin':42,'dagger':1,'arrow':12}

def displayInventory(stuff):
    item_total=0
    print('Inventory:')
    for k,v in stuff.items():
         print(k+ ' '+str(v))
         item_total=item_total+v

    print('total number of items: '+str(item_total))
        
displayInventory(game_item)

 

#练习5:返回一个字典表示更新过的物品清单

 #练习5:返回一个字典表示更新过的物品清单
def displayInventory(stuff):
    item_total=0
    print('Inventory:')
    for k,v in stuff.items():
         print(str(v)+' '+k)
         item_total=item_total+v

    print('total number of items: '+str(item_total))

def addToInventory(inventory, addedItems):
    for i in addedItems:
        if i in inventory:
        #if i in inventory.keys():
            inventory[i]+=1 #inventory[i]=inventory[i]+1
        else:
            #inventory[i]=1
            inventory.setdefault(i, 1)
    return inventory

inv = {'gold coin': 42, 'rope': 1}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
inv = addToInventory(inv, dragonLoot)
#print(inv) #{'gold coin': 45, 'rope': 1, 'dagger': 1, 'ruby': 1}
displayInventory(inv)

 

第6章 字符串操作


#处理字符串:
a="what's" #双引号内单引号不用转义
a='what\'s'#单引号内单引号要转义
print(r'what\'s') #字符串开始前加上r,忽略转义
print(#'''dear:,
bob
#''') #三重引号的多行字符串,不需要转义
a[0] #字符串的下标
a[0:2] #字符串的切片
'a' in a #列表的下标、切片、in、not in等操作都可以用于字符串


#字符串的方法
spam='Hello word!'
spam=spam.upper() #转换成大写
spam=spam.lower() #转换成小写
spam.islower() #判断是否小写
spam.isupper() #如果字符串至少有一个字母,并且所以字母都是大写或小写,返回True

#常用的isX字符串方法
spam.isalpha() #如果字符串只包含字母,并且非空,返回True
spam.isalnum() #如果字符串只包含字母和数字,并且非空,返回True
spam.isdecimal() #如果字符串只包含数字字符,并且非空,返回True
spam.isspace() #如果字符串只包含空格、制表符和换行符,并且非空,返回True
spam.istitle() #如果字符串只包含以大写字母开头后面都是小写字母的单词,返回True

spam.startswith('H') #以某字符串开始,真返回True
spam.endswith('word!') #以某字符串开始,真返回True

#join()方法:调用列表,返回字符串,格式为:'分隔符'.join(str)
spam=['Hello' ,'word']
','.join(spam) #返回'Hello,word'

b='Hello' +','+'word'
print(b) #结果同上

#split()方法:针对字符串调用,返回列表,格式为:str.split('分隔符,默认空白字符串’)
spam='Hello word
spam.split()


#rjust()、ljust()、center()对齐文本
#方法返回调用它们的字符串填充版本,默认通过插入空格对齐文本
#用法:方法(长度,填充字符(默认空格))
'hello'.rjust(10) #右对齐
'hello'.ljust(10) #左对齐
'hello'.ljust(10,'*')
'hello'.center(10)
'hello'.center(10,'*') #居中


#删除空白字符
'hello word'.strip() #删除左边或右边
'hello word'.lstrip() #删除左边
'hello word'.rstrip() #删除右边
'hello word'.strip('herd') #指定哪些字符被删除,删除两端出现的h、e、r、d,字符串顺序不重要

str.() #格式化字符串的函数,通过{}接受参数
spam.format()
"{} {}".format("hello", "world") # 不设置指定位置,按默认顺序


#isX字符串方法可用于验证用户输入

#isX字符串方法可用于验证用户输入 
  #例如:反复询问用户年龄和口令,直到提供有效输入
while True:
    print('Enter your age:')
    age=input()
    if age.isdecimal():
        break
    print('Please enter a number for your age')

while True:
    print('Select a new password (letters and numbers)')
    password=input()
    if age.isalnum():
        break
    print('passwors can only have letters and numbers')


 #如果密码错误,提示还有几次输入机会
d={'rope':1,'torch':6,'glod coin':42,'dagger':1,'arrow':12}
count = 5
while True:
    password = input('请输入您的密码:')
    if password in d.values():
        print('进入系统')
        break
    else:
        count -= 1
        print('您输入的密码不正确,还有{}次输入机会'.format(count))
        continue


 #如果要三次输入不对,则账户被锁定呢? 有问题?
d={'a':'12a','b':'aaa','c':'ccc'}
count = 5
while True:
    password = input('请输入您的密码:')
    if password not in d.values():
            count -= 1
            print('您输入的密码不正确,还有{}次输入机会'.format(count))
            if count==0:
                print('账户被锁定')
                break
        else:
            print('进入系统')
            break

################第7章 模糊匹配与正则表达式############################################
#python中的正则表达式都在re模块中,使用时要导入。
#python中使用正则表达式步骤:
#1.用imoport re 导入正在表达式模块;
#2.用re.compile()函数创建一个regex对象(使用原始字符串)
#3.向regex对象对象的search()方法传入想查找的字符串。
#它返回一个match对象,包含被查找字符串中的“第一次”匹配的文本
#4.match对象的group方法,传入0或不传入参数,返回实际匹配的字符串
#'''
import re
message='call me at 415-555-1011 tomorrow'
phone=re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')
mo=phone.search(message) #返回一个match对象,match对象调用group方法返回实际匹配的文本
print(mo.group()) #group方法不传人参数,返回匹配的整个文本
#'''
#'''
#利用括号分组
#添加括号在正则表达式中创建分组,group(参数)获取分组
#正则表达式中的第一对括号是第1组,第二对括号是第2组。
#向group传递参数1或2匹配文本的不同部分,传入0或不传入参数,返回整个匹配的文本
import re
message='call me at 415-555-1011 tomorrow'
phone=re.compile(r'(\d\d\d)-(\d\d\d)-(\d\d\d\d)')
mo=phone.search(message)
print(mo.group(1))
print(mo.group(2))
print(mo.group(3))

#如果想要一次获取多个分组,使用groups()方法进行多重赋值
mo=phone.search(message)
print(mo.groups()) #返回('415', '555', '1011')
a,b,c=mo.groups()
print(a)
print(b)
print(c)

#用管道匹配多个分组: |
#希望匹配多个表达式中的一个时,就可以使用|
import re
message='today and tomorrow'
phone=re.compile(r'today|and')
mo=phone.search(message)
print(mo.group()) #返回第一次出现的匹配文本作为match对象


import re
message='today and tomorrow'
phone=re.compile(r'to(day|morrow)')
mo=phone.search(message)
print(mo.group()) #返回第一次出现的匹配文本作为match对象
print(mo.group(1)) #返回第一个括号分组内第一次出现的匹配文本


# 问号? 实现可选匹配
#匹配?号之前的分组零次或一次
phone=re.compile(r'to(and)?day')

# 星号* 实现可选匹配
#匹配*号之前的分组零次或多次
phone=re.compile(r'to(and)*day')

# +号 实现可选匹配
#匹配+号之前的分组一次或多次
phone=re.compile(r'to(and)+day')


#用花括号{}匹配特定次数,如
#(ha){3}:匹配3次
#(ha){3,}:匹配3次或更多
#(ha){3,5}:匹配3-5次
#(ha){,5}:匹配0-5次
import re
a='hahaha'
phone=re.compile(r'(ha){3}')
mo=phone.search(a)
print(mo.group())

#和非贪心匹配
#贪心匹配:匹配尽可能长的字符串
#非贪心匹配:匹配尽可能短的字符串
#问号在正则表达式中有两种含义:声明非贪心匹配或表示可选的分组
import re
a='hahaha'
phone=re.compile(r'(ha){2,3}?')
mo=phone.search(a)
print(mo.group())

#findall()方法
#与search()方法相比:search()方法返回一个match对象,包含被查找字符串中的“第一次”匹配的文本
#findall()方法返回一个字符串列表,包含被查找字符串中的所有匹配
#findall()方法调用在没有分组的正则表达式上,返回一个匹配字符串的列表
#findall()方法调用在有分组的正则表达式上,返回一个匹配字符串的元组的列表

import re
message='call me at 415-555-1011 tomorrow,415-555-1012'
phone=re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')
mo=phone.findall(message)
print(mo) #['415-555-1011', '415-555-1012']

#如果在正则表达式中有分组,则findall将返回元组的列表,
#每个元组表示一个找到的匹配,其中的项就是正则表达式中每个分组的匹配字符串
import re
message='call me at 415-555-1011 tomorrow,415-555-1012'
phone=re.compile(r'(\d\d\d)-(\d\d\d)-(\d\d\d\d)')
mo=phone.findall(message)
print(mo) #[('415', '555', '1011'), ('415', '555', '1012')]

#字符分类p124:主要用于缩短正则表达式
#用方括号建立自己的字符分类
import re
message='call me at 415-555-1011 tomorrow,415-555-1012'
phone=re.compile(r'[a-zA-Z0-9]') #匹配所有小写字母、大写字母和数字
mo=phone.findall(message)
print(mo)

#用方括号建立自己的字符分类
import re
message='call me at 415-555-1011 tomorrow,415-555-1012'
phone=re.compile(r'[^a-zA-Z0-9]') #开始处插入^,匹配所有非小写字母、大写字母和数字
mo=phone.findall(message)
print(mo)

phone=re.compile(r'^hello') #匹配以hello开始的字符串
phone=re.compile(r'\d$') #匹配以0-9结尾的字符串
phone=re.compile(r'^\d+$') #匹配开始到结束都是数字的字符串

#通配字符
#.(句点),只匹配一个字符,匹配除换行符之外的所有单个字符
import re
phone=re.compile(r'.at')
mo=phone.findall('the cat in the hat sat on the fiat mat')
print(mo) #['cat', 'hat', 'sat', 'iat', 'mat']

#点星匹配除换行符外的所有字符
#点星为贪心匹配,若要显示非贪心匹配,添加问号?
import re
phone=re.compile(r'first name :(.*) last name:(.*)')
mo=phone.findall('first name :AI last name:BI')
print(mo) #[('AI', 'BI')]

import re
phone=re.compile(r'first name :(.*) last name:(.*)')
mo=phone.search('first name :AI last name:BI')
print(mo.group(1))
print(mo.group(2))

phone=re.compile(r'<.*?>') #声明非贪心匹配

#用句点匹配换行符:通过传入re.dotall作为re.compile()的第二个参数
import re
char=re.compile('.*')
mo=char.search('ss ss .\nss ss\n aa')
print(mo.group()) #返回ss ss .

import re
char=re.compile('.*',re.DOTALL)
mo=char.search('ss ss .\nss ss\n aa')
print(mo.group())

#使用正则表达式时不区分大小写
#通过向re.compile()传入re.IGNORECASE或re.I作为re.compile()的第二个参数
import re
char=re.compile('a',re.I)
mo=char.search('Aa')
print(mo.group())

#用sub()方法替换字符串
import re
phone = "2004-959-559 # 这是一个国外电话号码"
mo=re.compile(r'#.*$') #替换#号至结尾的字符
mo1=mo.sub("",phone)
print(mo1) #2004-959-559

#上式可以简化成下式的写法
#re.sub(pattern, repl, string, count=0, flags=0)
#参数:
#pattern : 正则中的模式字符串。
#repl : 替换的字符串,也可为一个函数。
#string : 要被查找替换的原始字符串。
#count : 模式匹配后替换的最大次数,默认 0 表示替换所有的匹配。

import re
phone = "2004-959-559 # 这是一个国外电话号码"
# 删除字符串中的 Python注释
num = re.sub(r'#.*$', "", phone)
print("电话号码是:"+num) #电话号码是:2004-959-559

#'''
#至此:正则表达式的写法可简化
#https://www.runoob.com/python/python-reg-expressions.html

################第8章 读写文件############################################
#路径:windows用倒斜杠\,linux和os x上用反斜杠/
#os.path.join()函数:在不同系统上创建正确的路径

#'''
import os
print(os.path.join('usr','bin','spam')) #返回usr\bin\spam
os.getcwd() #获取当前工作目录
os.chdir('路径') #修改当前工作目录
os.makedirs('D:\personal_file\python\code\data') #创建data文件夹
os.mkdir("test") #创建目录test
os.listdir('D:\personal_file\python\code') #返回文件名中文件字符串列表
os.walk(path) #传入一个文件夹路径,返回3个值
os.rename( "test1.txt", "test2.txt" ) #重命名文件test1.txt到test2.txt
os.remove("test2.txt") #删除一个已经存在的文件test2.txt
os.rmdir("/tmp/test") # 删除"/tmp/test"目录,在删除这个目录之前,它的所有内容应该先被清除。

os.path.getsize('D:\personal_file\python\code\circle.py') #返回文件的字节数
os.path.abspath(path) #返回相对路径的绝对路径
os.path.abspath('.')
os.path.isabs(path) #绝对路径返回True,相对路径返回False
os.path.realpath(path,start) #返回从start路径到path的相对路径的字符串
os.path.exists(path) #检查文件或文件夹是否存在
os.path.isdir(path) #判断是否是文件夹
os.path.isfile(path) #判断是否是一个文件
os.unlink(path) #删除path处的文件
os.rmdir(path) #删除空文件夹path

#检查要删除的文件是否已.txt结尾
import os
for filename in os.listdir():
if filename.endwith('.txt'):
os.unlink(filename)
print(filename)

#遍历目录树
import os
for foldername,subfolders,filenames in os.walk('D:\personal_file\python'):
print('the current folder is '+foldername)

for subfolder in subfolders:
print('subfolder of '+foldername+': '+subfolder)
for filename in filenames:
print('file inside '+foldername +':'+filename)


#统计某个目录下所有文件的总字节数
import os
totalsize=0
for filename in os.listdir('D:\personal_file\python\code'):
totalsize=totalsize+os.path.getsize(os.path.join('D:\personal_file\python\code',filename))
print(totalsize)


#文件的读写过程open()

#用Python内置的open()函数打开一个文件,创建一个file对象,相关的方法才可以调用它进行读写
#open(file,mode)
#mode='r' 只读模式打开,默认
#mode='w' 写模式。如果该文件已存在则打开文件并从开头开始编辑(即原有内容会被删除)。如果该文件不存在则创建新文件。
#mode='a' 追加模式,打开一个文件用于追加。如果该文件已存在,从末尾新增内容写入。如果该文件不存在,创建新文件进行写入。
#更多:https://www.runoob.com/python/python-files-io.html

#读取文件
#file=open('D:\personal_file\python\code\test.txt') #写法错误?
file=open('D:\\personal_file\\python\code\\test.txt') #写法正确,创建file对象,默认只读r
print(file.read()) #read方法读取文件内容

#写文件
#write()方法需要自己在末尾添加换行字符
file=open('D:\\personal_file\\python\code\\test.txt','w') #写模式
file.write('hello!')
file.close #关闭该文件
file=open('D:\\personal_file\\python\code\\test.txt')
print(file.read())


file=open('D:\\personal_file\\python\code\\test.txt','a') #追加模式
file.write('\nhello!')
file.close #关闭该文件
file=open('D:\\personal_file\\python\code\\test.txt')
print(file.read())

#用shelve模块保存变量:用于保存python程序中的数据
import shelve
shelfFile=shelve.open('mydata') #传入文件名
cat=['a','b','c']
shelfFile['cat']=cat #shlefile['键']=值
shelfFile.close()
#windows上运行上面代码,当前目录下会有3个新文件:mydata.bak、mydata.dat、mydata.dir
shelfFile=shelve.open('mydata') #使用shelve模块重新打开文件,shelf值不用制定模式,因为它们打开后既能读也能写
type(shelfFile) #返回<class 'shelve.DbfilenameShelf'>
print(shelfFile['cat'])

#就像数据字典一样,shelf值有keys()和values()方法,返回shelf值对应的类似列表值(不是真正的列表)
#所以应该将它们传递给list()函数,返回列表的形式
shelfFile=shelve.open('mydata')
print(list(shelfFile['cat']))
#'''
################第9章 组织文件############################################
#'''
import shutil
#复制文件或文件夹:shutil.copy类似于cp命令
shutil.copy('D:\personal_file\python\code\hello.py','D:\personal_file\python\hello.py')
#移动和改名文件或文件夹:shutil.move类似于move命令
shutil.move(source,destination)
#永久删除文件和文件夹
shutil.rmtree(path) #删除path处的文件夹(不可恢复)
#用send2trash模块安全删除
#安装第三方模块send2trash:使用pip命令
#cmd中切换到:D:\python\Scripts>pip install send2trash
#将文件删除到电脑回收站
import send2trash
send2trash.send2trash('D:\personal_file\python\Python_copy.docx')

#用zipfile模块压缩文件
#与open()函数用法类似
import zipfile,os
os.chdir('D:\\personal_file\\python\\test')
print(os.getcwd())
example=zipfile.ZipFile('example.zip') ?练习有错
example.namelist()
#'''


################第10章 调试############################################
#抛出异常raise
#常看到raise语句在一个函数中,try和except在调用该函数的代码中
#raise Exception('error')

 

标签:入门,spam,python,mo,编程,列表,字符串,print,name
From: https://www.cnblogs.com/lizixi/p/17485290.html

相关文章

  • 网络编程
    网络概述:多台相互连接的计算机资源共享    3.交换数据网络的类型分类按拓扑分类:星型结构 树型结构 总线型线程 环形结构 网状架构按范围分类:局域网LAN 城域网MAN 广域网WAN 补充:个人局域网PAN 互联网Internet按传输方式分类:有线网络 无线网络 网络......
  • python之冒泡排序
    冒泡排序原理:;两两比较,将(大、小)的元素往右移importrandoma=random.sample(range(0,10),4)#随机生成4个1到10之内的数字lenth=len(a)#获取长度print(a)#需要冒泡排序的列表#比较(趟数),最后一趟无需比较,所以减1forjinrange(lenth-1):#-1:最后一......
  • Python设计模式-07-装饰模式
    装饰模式是一种结构型设计模式,它允许我们动态地将行为添加到对象中,而不需要使用继承。装饰模式通常包括以下几个角色:抽象组件(Component):定义了一个接口,用于被装饰对象和装饰器共同实现。具体组件(ConcreteComponent):实现了抽象组件定义的接口,并提供了默认的行为。抽象装饰......
  • Python设计模式-17-外观模式
    外观模式是一种结构型设计模式,它为复杂的子系统提供了一个简单的接口,从而隐藏了子系统的复杂性。外观模式通常包括以下几个角色:外观(Facade):提供了一个简单的接口,用于访问子系统中的一组接口。子系统(Subsystem):实现了子系统的功能,并处理外观对象指派的任务。下面是一个简单......
  • Python设计模式-18-中介模式
    中介模式是一种行为型设计模式,它允许对象之间通过一个中介对象进行通信,从而减少对象之间的直接耦合。中介模式通常包括以下几个角色:中介者(Mediator):定义了一个接口,用于与各个同事对象通信,并协调它们之间的交互。具体中介者(ConcreteMediator):实现了中介者定义的接口,并协调各个......
  • Python设计模式-19-备忘录模式
    备忘录模式是一种行为型设计模式,它允许我们在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。备忘录模式通常包括以下几个角色:发起人(Originator):定义了一个接口,用于创建备忘录对象和恢复对象状态。备忘录(Memento):存储发起人对象的内部状态。管理......
  • Python设计模式-20-迭代器模式
    迭代器模式是一种行为型设计模式,它允许我们按照顺序访问一个聚合对象中的元素,而不需要暴露该对象的内部表示。迭代器模式通常包括以下几个角色:迭代器(Iterator):定义了一个接口,用于按照顺序访问聚合对象中的元素。具体迭代器(ConcreteIterator):实现了迭代器定义的接口,并维护了当......
  • Python设计模式-21-解释器模式
    解释器模式是一种行为型设计模式,它定义了一种语言,用于解释和执行特定的任务。解释器模式通常包括以下几个角色:抽象表达式(AbstractExpression):定义了一个接口,用于解释和执行特定的任务。终结符表达式(TerminalExpression):实现了抽象表达式定义的接口,并表示语言中的终结符。......
  • Python设计模式-22-模板模式
    模板模式是一种行为型设计模式,它定义了一个算法的骨架,将一些步骤延迟到子类中实现。模板模式通常包括以下几个角色:抽象类(AbstractClass):定义了一个算法的骨架,其中包含一些抽象方法,用于延迟到子类中实现。具体类(ConcreteClass):实现了抽象类定义的接口,并实现了其中的抽象方法......
  • Python设计模式-06-代理模式
    代理模式是一种结构型设计模式,它提供了一个代理对象来控制对另一个对象的访问。代理模式通常包括以下几个角色:抽象主题(Subject):定义了代理对象和真实对象的公共接口,可以是一个抽象类或接口。真实主题(RealSubject):定义了代理对象所代表的真实对象。代理(Proxy):持有一个真实对象的......