2019年7月

可选参数 说明

-F dist文件夹中生成一个程序demo.exe文件,适用于一个模块没有多依赖.py文件

-D 默认选项,除了主程序demo.exe外,还会在在dist文件夹中生成很多依赖文件,推荐使用这个

-c 默认选项,只对windows有效,使用控制台

-w 只对windows有效,不使用控制台

-p 设置导入路径

-i 给生成的demo.exe文件设置一个自定义的图标

--key 后面接加密参数

使用 Pipenv减小打包文件的大小

1.安装 Pipenv

pip install pipenv

2.

pipenv install --python 3.9

(版本为已安装的版本)

3.在命令行下激活环境

pipenv shell

4.在虚拟环境下安装 Pyinstaller 和你自己的脚本依赖的第三方库

pipenv install pyinstaller
pipenv install pyqt5
....

pipenv install -i https://pypi.tuna.tsinghua.edu.cn/simple

5.常用指令

创建环境: pipenv install
激活环境: pipenv shell
退出环境: exit
删除环境: pipenv --rm

安装依赖
安装依赖到虚拟环境pipenv install [package]或者pip install -r requirements.txt

查看虚拟环境中的所有安装的包
如果没有进入虚拟环境中,则需要先使用pipenv shell进入虚拟环境。然后使用pip list查看,或者使用pip freeze > requirements.txt导出所有安装的包。

删除/清空环境的依赖
删除指定的包:pipenv uninstall [package]
清空:pipenv uninstall --all或pipenv uninstall --all-dev

1.国外手机判断

def iphonenum(txt):
    if len(txt) != 12:
        return False
    for i in range(3):
        if not txt[i].isdecimal():
            return False
    if txt[3] != '-':
        return False
    for j in range(4, 7):
        if not txt[j].isdecimal():
            return False
    if txt[7] != '-':
        return False
    for l in range(8, 12):
        if not txt[l].isdecimal():
            return False
    return True

print('请输入手机号码:', end='')
k =input()
print('判断是否为手机号码:', iphonenum(k))

2.查找文本中的手机号码

def iphonenum(txt):
    if len(txt) != 12:
        return False
    for i in range(3):
        if not txt[i].isdecimal():
            return False
    if txt[3] != '-':
        return False
    for j in range(4, 7):
        if not txt[j].isdecimal():
            return False
    if txt[7] != '-':
        return False
    for l in range(8, 12):
        if not txt[l].isdecimal():
            return False
    return True

mes='Call me at 415-555-1101 tomorrow.415-666-7845 is my office.'
for m in range(len(mes)):
    n = mes[m:m+12]
    if iphonenum(n):
        print('找到的电话号码是:', n)
print('查找完成')

3.判断国内手机号码

def iphonenum(txt):
    if len(txt) != 11:
        return False
    for i in range(11):
        if not txt[i].isdecimal():
            return False
    return True

print('请输入手机号码:', end='')
k =input()
print('判断是否为手机号码:', iphonenum(k))

4.正则表达式
例一:

import re
phonenum = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')
k = 'my phone Number is 400-410-8888, and my office number is 411-808-9999·'
mo = phonenum.search(k)
print('打印出找到的电话号码:', mo.group())
print(mo.groups())

例二:

import re
phonenum = re.compile(r'(\d\d\d)-(\d\d\d-\d\d\d\d)')
k = 'my phone Number is 400-410-8888, and my office number is 411-808-9999'
mo = phonenum.search(k)
print('1:', mo.group())
print('2:', mo.group(1))
print('3:', mo.group(2))
print('4:', mo.groups())
j,  l = mo.groups()
print('5:', j)
print('6:', l)
m = mo.groups()
n=list(m)
print('7:', n)
o=tuple(n)
print('8:', o)
p='-'.join(o)
print('9:', p)

5.用管道匹配分组

import re
ph = re.compile(r'Batman|Tina Fey')
a = "Batman and Tina Fey"
b = "Tina Fey and Batman"
mo1 = ph.search(a)
mo2 = ph.search(b)
print('1:', mo1.group())
print('2:', mo2.group())

phx = re.compile(r'Bat(man|mil|cop|kk)')
c = "Batman and Batmil and Batcop and Tina"
mo3 = phx.search(c)
print('3:', mo3.group())
print('4:', mo3.groups())
print('5:', mo3.group(1))
print(''' ////////以下是4和5转换为的列表''''')
d =list(mo3.groups())
print('6:',d)
e =mo3.group(1)
f = e.split()
print('7:', f)

6.问号实现可选匹配

import re
px = re.compile(r'Bat(wo)?man')
z = 'The Adventures of Batman'
x = 'The Adventures of Batwoman'
c = 'The Adventures of Batwowoman Batman'
mo1 = px.search(z)
print('1:', mo1.group())
print('1:', mo1.groups())
print('1:', mo1.group(1))
mo2 = px.search(x)
print('2:', mo2.group())
print('2:', mo2.groups())
print('2:', mo2.group(1))
mo3 = px.search(c)
print('3:', mo3.group())
print('3:', mo3.groups())
print('3:', mo3.group(1))

7.星号实现0个或多个匹配

import re
px = re.compile(r'Bat(wo)*man')
z = 'The Adventures of Batman'
x = 'The Adventures of Batwoman'
c = 'The Adventures of Batwowoman Batman'
mo1 = px.search(z)
print('1:', mo1.group())
print('1:', mo1.groups())
print('1:', mo1.group(1))
mo2 = px.search(x)
print('2:', mo2.group())
print('2:', mo2.groups())
print('2:', mo2.group(1))
mo3 = px.search(c)
print('3:', mo3.group())
print('3:', mo3.groups())
print('3:', mo3.group(1))

8.加号实现一个或多个匹配

import re
px = re.compile(r'Bat(wo)+man')
x = 'The Adventures of Batwoman'
c = 'The Adventures of Batwowoman Batman'
mo2 = px.search(x)
print('2:', mo2.group())
print('2:', mo2.groups())
print('2:', mo2.group(1))
mo3 = px.search(c)
print('3:', mo3.group())
print('3:', mo3.groups())
print('3:', mo3.group(1))

9.花括号实现特定次数匹配

import re
px = re.compile(r'Bat(wo){3,5}man')
x = 'The Adventures of Batwowowoman'
c = 'The Adventures of Batwowowowoman Batman'
mo2 = px.search(x)
print('2:', mo2.group())
print('2:', mo2.groups())
print('2:', mo2.group(1))
mo3 = px.search(c)
print('3:', mo3.group())
print('3:', mo3.groups())
print('3:', mo3.group(1))
print('Python正则表达式默认是贪心的,在有二义的情况匹配最长字符 ')
10.findall()使用方法
import re
phonenum = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')
k = 'my phone Number is 400-410-8888, and my office number is 411-808-9999·411-785-1360,361-879-1360'
mo = phonenum.findall(k)
for i in range(len(mo)):
    k =mo[i]
    print('打印出找到的第'+str(i+1)+'个电话号码:', k)

10.字符分类

'''
\d   0-9的数字
\D   除0-9以外的数字
\w   任何数字字母或下划线字符(匹配单词字符)
\W   除字母,数字和下划线以外的任何字符
\s    空格,制表符,换行符(匹配空白字符)
\S    除空格,制表符,换行符以外的任何字符
'''
print(
'''
\d   0-9的数字
\D   除0-9以外的数字
\w   任何数字字母或下划线字符(匹配单词字符)
\W   除字母,数字和下划线以外的任何字符
\s    空格,制表符,换行符(匹配空白字符)
\S    除空格,制表符,换行符以外的任何字符
''')
import re
ce =re.compile(r'\d+\s+\w')
le = re.compile(r'\d+\s')
qe = re.compile(r'\d+')
ke='11 text,23 your,89 kill'
ve =ce.findall(ke)
print('输出第一次从字符串中提取的列表:', ve)
be = ' '.join(ve)
print('把列表转换为字符串:', be)
ne =le.findall(be)
print('输出第二次从字符串中提取的列表:', ne)
me =[]
for i in range(len(ne)):
    o =ne[i]
    p = o.strip()
    me.append(p)
print('输出去空格过后的数字列表:', me)
tuple1 = tuple(me)
print('输出转换的元组:', tuple1)
str2=' '.join(tuple1)
print('输出字符串:', str2)
we = qe.findall(str2)
print('再次转换为列表:', we)
ee = ''.join(we)
print('把所有数字链接:', ee)

11.建立自己的字符分类

#建立 自己的字符分类
import re
vowe =re.compile(r'[aeirAidR]')
ve = 'Administrator,try agin'
ce = vowe.findall(ve)
print(ce)

12.插入字符和美元字符

import re
ne = re.compile(r'\d$')
ve = re.compile(r'^Hello')
ce = 'Hello World!'
me = "my number is 42"
be =ne.search(me)
ae = ne.findall(me)
print(be)
print(ae)
xe = ve.search(ce)
ze= ve.findall(ce)
print(xe)
print(ze)

13.通配字符

import re
me = re.compile(r'.at')
ne = 'the cat in the hat.sat on the flat mat'
be = me.findall(ne)
k =input('请加入一个以at结尾的单词:')
be.append(k)
print(be)
ve =' '.join(be)
ce=''.join(be)
print(ve)
print(ce)

14.用点-星匹配所有字符

import re
me = re.compile(r'First Name:(.*) Last Name:(.*)')
ne = 'My First Name:Eric Last Name:Qiu'
be =me.search(ne)
print(be)
print(be.group())
print(be.groups())
print(be.group(1))
print(be.group(2))

15句点字符匹配换行

import re
me = re.compile(r'.*')
ve =re.compile(r'.*', re.DOTALL)
ne = 'My First Name:Eric \nLast Name:Qiu'
be = me.search(ne)
ce = ve.search(ne)
print(be.group())
print(ce.group())

16.不区分大小写

import re
me1 = re.compile('RoboCop')
me1 = re.compile('RObOCOP')
me1 = re.compile('robOcop')
me1 = re.compile('RobocOp')
ne = re.compile(r'robocop', re.I)
be = "RoboCop is part man.part machine,all cop"
ve = ne.search(be)
print(ve.group())

17.使用sub()方法替换替换字符

import re
ne = re.compile(r'Agent \w+')
ve = ne.sub('CENSORED','Agent gave is part man.part machine,all cop')
print(ve)

1.转义符

\'        单引号
\"        双引号
\t        制表符
\n        换行符
\\        倒斜杠

2.原始字符串
在前面加上r
例子:

>print(r"my \name is Bob")
my \name is Bob
>print("my \name is Bob")
my 
ame is Bob

3.三重引号的多行字符串

>print('''my
name
is
Bob
''')

输出的结果为:

my
name
is
Bob

4,多行注释

#表示这一行注释
"""This
is
python
"""

def he():
    """This is 
        Python
        """
    print('Hello!')
he()

输出的结果为:
Hello!

5.字符串下标和切片

>spam = 'Hello World!'
>spam[0]
'H'
>spam[0:5]
'Hello'

6.字符串的in和not in

>spam = 'Hello World!'
>'Hello' in 'Hello world'
True
>'HELLO' in 'Hello world'
False
>' ' in spam
True
>'cat' not in spam
True

7.字符串方法upper()&lower()&isupper()&islower()
upper()&lower()
字符串小大写转换,返回的也是字符串:

>spam = 'Hello'
>spam.upper()
>print(spam)
'HELLO'
>spam.lower()
>print(spam)
hello

isupper()&islower()
字符串的大小写判断,返回的值为布尔值:

>spam = 'Hello'
>spam.isupper()
False
>spam.islower()
False

8.isX字符串方法
除上面的isupper&islower以外,还有一下

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

例子:

while True:
    print('请输入你的年龄: ', end='')
    age=input()
    if age.isdecimal():
        break
    elif age.isalpha():
        print('''
        你输入的年龄是字符!
        年龄错误!
        请再次重试.''')
    elif age.isalnum():
        print('你输入的年龄包含数字和字母!请再次重试.')
    else:
        print('未知的格式!请再次重试')
print('你的年龄是:'+age)

9.startswith()&endswith()的使用方法
验证开头和结尾是否为对应的值,返回的也是布尔值:

>spam = 'Hello World!'
>spam.startswith('Hello')
True
>spam.endswith('World!')
True
>spam.endswith('Hello')
False

10.join()和split()的使用方法
join()使列表通过某一个字符分开变为字符串
例子:

spam = ['my', 'name', 'is', 'Eric']
k =' '.join(spam)
print(k)

输出的结果为

my name is Eric

split()使字符串通过某一字符分开变为列表
例子:

spam = 'my name is Eric'
j =spam.split()
print(j)

输出的结果为

['my', 'name', 'is', 'Eric']

10.rjust()&ljust()¢er()对齐的使用

spam = 'my name is Eric'
k = spam.rjust(30)
print('输出k的值(右对齐30个字符):', k)
j = spam.ljust(30)
print('输出j的值(左对齐30个字符):', j)
i = spam.center(30)
print('输出i的值(居中对齐30个字符):',i)
k = spam.rjust(30, '#')
print('输出k的值(右对齐30个字符):', k)
j = spam.ljust(30, '*')
print('输出j的值(左对齐30个字符):', j)
i = spam.center(30, '-')
print('输出i的值(居中对齐30个字符):',i)

11.strip()&rstrip()&lstrip()去除空格使用

spam = ' Hello World! '
i = spam.strip()
print('使用strip()后的值:')
print(i)
j = spam.rstrip()
print('使用rstrip()后的值:')
print(j)
k = spam.lstrip()
print('使用lstrip()后的值:')
print(k)

12.pyperclip模块复制粘贴字符串

#使用前确保已经安装pyperclip模块
import pyperclip
spam = ' Hello World! '
pyperclip.copy(spam)
print(pyperclip.paste())

1.字典和数据类型

mycat ={'size':'fat', 'name':'Vice', 'color':'gray'}
print("输出猫的名字为:", mycat['name'])
print('my cat name is '+mycat['name'])

2.字典与列表

spam=['dogs','cat','pig']
bacon = ['pig','cat','dogs']
print("spam=['dogs','cat','pig']")
print("bacon = ['pig','cat','dogs']")
if spam == bacon:
    print("True")
else:
    print('False')
    
egg = {'name':'jim', 'color':'gray'}
ham = {'color':'gray', 'name':'jim'}
print("egg = {'name':'jim', 'color':'gray'}")
print("ham = {'color':'gray', 'name':'jim'}")
if egg == ham:
    print('True')
else:
    print('False')
while True:
    print('请输入egg中的值:',end=' ')
    k = input()
    try:
        print(egg[k])
        break
    except KeyError:
        print('输入的字典中没有')

3.keys()&values&items()使用方法

egg = {'name':'jim', 'color':'gray'}
for v in egg.values():
    print("打印出值:", v)
    
print("\n")
for k in egg.keys():
    print("打印出键:", k)
print("\n")

for i in egg.items():
    print("打印出键-值:", i)
    

4.检查字典中的键或值

egg = {'name':'jim', 'color':'gray'}
"name" in egg.keys()
'gray' in egg.values()

5.get()使用

spam={'name':'jim', 'color':'gray'}
print('获取Name的值:', spam.get('name', 0))
print('输入需要查找的键:', end=' ')
j = input()
k =spam.get(j, 0)
if k == 0:
    print('字典中没有'+str(j)+'的值')
else:
    print('键'+str(j)+'的值为:', k)

6.setdefault()使用:
1:

spam={'name':'jim', 'color':'gray'}
while True:
    print('输入需要查找的键:', end=' ')
    j = input()
    k =spam.get(j, 0)
    if k == 0:
        print('字典中没有'+str(j)+'的值')
        print('输入'+str(j)+'的值:', end='')
        i =input()
        spam.setdefault(j, i)
        print('输出字典spam:', spam)
    else:
        print('键'+str(j)+'的值为:', k)
        break

2:

message = "John Smith was a good math student at a high school. He loved his computer. He came home early every day. Then he worked with it till midnight. But John was not a good English student, not good at all. He got an F in his English class. One day after school, John joined his computer to the computer in his high school office. The school office computer had the grades of all the students: the math grades, the science grades, the grades in arts and music, and grades in English. He found his English grade. An F! John changed his English grade from F to A. John’s parents looked at his report card. They were very happy. "
count={}
for char in message:
    count.setdefault(char, 0)
    count[char] = count[char]+1
print(count)

7.漂亮的打印pprint

import pprint
v = "John Smith was a good math student at a high school. He loved his computer. He came home early every day. Then he worked with it till midnight. But John was not a good English student, not good at all. He got an F in his English class. One day after school, John joined his computer to the computer in his high school office. The school office computer had the grades of all the students: the math grades, the science grades, the grades in arts and music, and grades in English. He found his English grade. An F! John changed his English grade from F to A. John’s parents looked at his report card. They were very happy. "
count={}
for char in v:
    count.setdefault(char, 0)
    count[char] = count[char]+1
pprint.pprint(count)

8.#字棋

the = {'top-L':'','top-M':' ','top-R':' ',
'mid-L':' ','mid-M':'','mid-R':' ',
'low-L':' ','low-M':' ','low-R':''}
print(the)

def bord(eh):
    print(eh['top-L']+'|'+eh['top-M']+'|'+eh['top-R'])
    print('-+-+-')
    print(eh['mid-L']+'|'+eh['mid-M']+'|'+eh['mid-R'])
    print('-+-+-')
    print(eh['low-L']+'|'+eh['low-M']+'|'+eh['low-R'])
turn = "X"
for i in range(9):
    bord(the)
    print('Turn for ' + turn+' . Move on which space?')
    move =input()
    the[move]= turn
    if turn == 'X':
        turn = "O"
    else:
        turn = "X"
bord(the)

9.嵌套字典列表

the = {'Alice':{'apples':5, 'pies':12}, 
'Bob':{'cup':3, 'apples':2}, 
'Jim':{'cup':6, 'pies':7}
}

def  tho(guess, item):
    num = 0
    for k, v in the.items():
        num += v.get(item, 0)
        print('k的值:', k)
        print("v的值:", v)
    return num

print('Number of things being brought:')
print('- apples '+str(tho(the, 'apples')))
print('- cup ' +str(tho(the, 'cup')))
print('- pies '+str(tho(the, 'pies')))

列表应用例子:
1.打印出家里所有猫的名字

catname=[]
while True:
    print("输入第"+str(len(catname)+1)+'只猫的名字'+'(或者不输入直接回车结束.):')
    name = input()
    if name == "":
        break
    catname = catname+[name]
print("The cat names are:" ,name)
i=0
for name in catname:
    i+=1
    print('第'+str(i) +"只猫的名字是:"+name)

2.用循环列表打印出:

for i in [1,2,3,4,5]:
    print(i)

3.列表中in的使用

spam = ['a','b','c','d']
while True:
    print('输入字母:')
    name = input()
    if name in spam:
        print("你输入的字母在列表中为:",name)
        break
    else:
        print('你输入的字母不在列表中。')

4.列表中not in的使用

spam = ['a','b','c','d']
i=0
while True:
    i+=1
    print('输入字母:')
    name = input()
    if name not in spam:
        print('你输入的字母不在列表中')
        continue
    else:
        print('你输入的字母在列表中为:',name)
        break
print('您使用了'+str(i)+'次猜中了列表中数字')

5.增强赋值

for i in range(5):
    i +=1
    print(i)
    k=7
    k -=1
    print(k)
    j =2
    j +=1
    j*=2
    print(j)
    l=10
    l +=1
    l /=2
    print(l)
    m=15
    m +=1
    m%=2
    print(m)
    print('\n')

6.列表中index查找索引位置

spam = ['a','b','c','d']
for i in range(1, 7):
    print('输入26个字母中的1个:')
    mu = input()
    if mu in spam:
        print('您输入的'+mu+'在列表中的'+str(spam.index(mu)+1)+"位置")
        break
    else:
        print("您输入的字母不在列表中")
if 0<i<6:
    print('您使用了'+str(i)+'次机会')
else:
    print('您的6次机会已使用完')

7.列表append添加值

spam = ['a','b','c','d']
for i in range(len(spam)):
    print('请输入第'+str(i+1)+'次需要添加的字母:',end=' ')
    mu = input()
    if mu != "j":
        spam.append(mu)
    elif mu == 'j':
        print('输入了错误的J')
        break
print(spam)

8.insert指定位置插入

import random
spam = ['a','b','c','d']
i = 1
while True:
    if i < 11:
        k = random.randint(0,4)
        print("输出第"+str(i)+"次k的值:",k)
        mu = input('请输入需要添加的字母:')
        spam.insert(k,mu)
        
    else:
        break
    i +=1
print("打印出现在的spam:",spam)

9.remove()删除列表中的元素
spam = ['a','b','c','d','a','b','c','d','a']
print("打印出现在的spam值:",spam)
for i in range(10):
    k=input('请输入需要删除的abcd中的一个字母')
    try:
        spam.remove(k)
        print("打印出删除过后的spam的值:",spam)
    except ValueError:
        print('列表中没有该元素了。',spam)

10.sort对列表排序

spam = []
for i in range(7):
    print('请给列表添加数字:',end='')
    j = int(input())
    if j != 99:
        spam.append(j)
    elif j == 99:
        print('输入了错误的数字:99')
        break
try:
    print("打印出已知的列表",spam)
    spam.sort(reverse=False)
    print('输出升序值',spam)
    spam.sort(reverse=True)
    print('输入降序值',spam)
except TypeError:
    print("你的列表是数字和字母混合,不能排序")

11.可变和不可变的数据类型

name = 'Zophie a cat'
print('输出name:',name)
newname =name[0:7]+'the'+name[8:12]
print("newname =name[0:7]+'the'+name[8:12]")
print('输出newname:',newname)

print('改变id')
eggs=[1,2,3]
print(id(eggs))
eggs=[4,5,6]
print(id(eggs))

print('不改变id')
egg=[1,2,3]
print(id(egg))
del egg[2]
del egg[1]
del egg[0]
egg.append(4)
egg.append(5)
egg.append(6)
print(id(egg))

12.元组数据类型

eggs = ('hello',42,0.5)
print('输出eggs[ 0]:',eggs[0])
print('输出eggs[1:3]:',eggs[1:3])
print('计算eggs的长度:',len(eggs))
13.list,tuple数据类型的相互转换
tuple1=(1,2,4,6)
list1 =[4,5,6,7]

print('打印转换前的tuple1:',tuple1)
print('打印转换后的tuple1:',list(tuple1))
print('打印转换前的list1:',list1)
print('打印转换前的list1:',tuple(list1))

14.引用

s = 42
while True:
    c=s
    s = 100
    print("输出s:",s,id(s))
    print("输出c:",c,id(c))
    break

sp = [0,1,2,3,4]
che =sp

print('sp的值为:',sp)
print('che的值为:',che)
while True:
    print('输入判断值0或者1:',end=' ')
    j = int(input())
    if j == 0:
        k =input('输出需要改变的值:')
        che[0]=k
        print('输出修改che[0]后che的值:',che,id(che))
        print('输出修改che[0]后sp的值:',sp,id(sp))
        break
    elif j == 1:
        k =input('输出需要改变的值:')
        sp[0]=k
        print('输出修改che[0]后che的值:',che,id(che))
        print('输出修改che[0]后sp的值:',sp,id(sp))
        break
    else:
        print('请输入0或者1')
        continue

15.传递引用

def egg(some):
    some.append('hello')
spam = [1,2,3,4]
egg(spam)
print(spam)

16.copy模块

import copy
spam= [1,'A',3,4,5]
cheese = copy.copy(spam)
cheese[1] = 2
print('输出spam的列表和ID:',spam,id(spam))
print('输出cheese的列表和ID:',cheese,id(cheese))