Python基础——模块和包与正则表表达式

一.模块

1.命名空间

命名空间表示标识符的可见范围。一个标识符可以在多个命名空间中定义,它在不同命题空间中的含义是互不相干的。

2.导入模块

(1)import 模块名

#p13_1.py
def c2f(cel):
    fah=cel*1.8+32
    return fah
def f2c(fah):
    cel=(fah-32)/1.8
    return cel
#p13_2.py
import p13_1
print("32摄氏度=%.2f华氏度"%p13_1.c2f(32))
print("99华氏度=%.2f摄氏度"%p13_1.f2c(99))

(2)from模块名import函数名

#p13_3.py
from p13_1 import c2f,f2c
print("32摄氏度=%.2f华氏度"%c2f(32))
print("99华氏度=%.2f摄氏度"%f2c(99))

(3)import模块名as新名字

#p13_4.py
import p13_1 as tc
print("32摄氏度=%.2f华氏度"%tc.c2f(32))
print("99华氏度=%.2f摄氏度"%tc.f2c(99))

3.__name__=='__main__'

#p13_5.pydef 
def c2f(cel):
    fah=cel*1.8+32
    return fah
def f2c(fah):
    cel=(fah-32)/1.8
    return cel
def test():
    print("测试,0摄氏度=%.2f华氏度" % c2f(0))
    print("测试,0华氏度=%.2f摄氏度" % f2c(0))
#p13_6.pydef 
def c2f(cel):
    fah=cel*1.8+32
    return fah
def f2c(fah):
    cel=(fah-32)/1.8
    return cel
def test():
    print("测试,0摄氏度=%.2f华氏度" % c2f(0))
    print("测试,0华氏度=%.2f摄氏度" % f2c(0))
if __name__=='__main__';
	test()

4.搜索路径

import sys
sys.path
['', 'D:\\Program Files\\Python310\\Lib\\idlelib', 'D:\\Program Files\\Python310\\python310.zip', 'D:\\Program Files\\Python310\\DLLs', 'D:\\Program Files\\Python310\\lib', 'D:\\Program Files\\Python310', 'D:\\Program Files\\Python310\\lib\\site-packages']

二.包

创建一个包的具体操作:
(1)创建一个文件夹用于存放相关的模块,文件夹的名字即包的名字。
(2)在文件夹中创建一个__init__.py的模块文件,内容可以为空。
(3)将相关的模块放入文件夹中。

1.Python的官方帮助文档

(1)Parts of the documentation
(2)Tutorial
(3)Library Reference
(4)Installing Python Models
(5)Distributing Python Models
(6)Language Reference
(7)Python Setup and Usage
(8)Python HOWTOs
(9)Extending and Embedding
(10)FAQs

2.Basic Examples

(1)调用__doc__属性,用print把带格式地打印出来。

import timeit
print(timeit.__doc__)
Tool for measuring execution time of small code snippets.

This module avoids a number of common traps for measuring execution
times.  See also Tim Peters' introduction to the Algorithms chapter in
the Python Cookbook, published by O'Reilly.

Library usage: see the Timer class.

Command line usage:
    python timeit.py [-n N] [-r N] [-s S] [-p] [-h] [--] [statement]

Options:
  -n/--number N: how many times to execute 'statement' (default: see below)
  -r/--repeat N: how many times to repeat the timer (default 5)
  -s/--setup S: statement to be executed once initially (default 'pass').
                Execution time of this setup statement is NOT timed.
  -p/--process: use time.process_time() (default is time.perf_counter())
  -v/--verbose: print raw timing results; repeat for more digits precision
  -u/--unit: set the output time unit (nsec, usec, msec, or sec)
  -h/--help: print this usage message and exit
  --: separate options from statement, use when statement starts with -
  statement: statement to be timed (default 'pass')

A multi-line statement may be given by specifying each line as a
separate argument; indented lines are possible by enclosing an
argument in quotes and using leading spaces.  Multiple -s options are
treated similarly.

If -n is not given, a suitable number of loops is calculated by trying
increasing numbers from the sequence 1, 2, 5, 10, 20, 50, ... until the
total time is at least 0.2 seconds.

Note: there is a certain baseline overhead associated with executing a
pass statement.  It differs between versions.  The code here doesn't try
to hide it, but you should be aware of it.  The baseline overhead can be
measured by invoking the program without arguments.

Classes:

    Timer

Functions:

    timeit(string, string) -> float
    repeat(string, string) -> list
    default_timer() -> float

(2)使用dir()函数可以查询到该模块定义了哪些变量、函数和类。

dir(timeit)
['Timer', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_globals', 'default_number', 'default_repeat', 'default_timer', 'dummy_src_name', 'gc', 'itertools', 'main', 'reindent', 'repeat', 'sys', 'template', 'time', 'timeit']

(3)s使用__all__可以帮助我们完成过滤操作。

timeit.__all__
['Timer', 'timeit', 'repeat', 'default_timer']

(4)名为__file__这一属性指明了该模块的源代码位置。

import timeit
timeit.__file__
'D:\\Program Files\\Python310\\lib\\timeit.py'

三.正则表达式

1.re模块

import re
print(re.search(r'FishC','I love FishC.com!'))

注意:
1.第一个参数是正则表达式模式,也就是要描述的搜索规则,需要使用原始字符串来写,因为这样可以避免很多不必要的麻烦。
2.找到后返回的范围是以下标为0开始的,这与字符串一样。如果找不到,它就返回None。

2.通配符

正则表达式也有所谓的通配符,在这里是用一个点号(.)来表示,它可以匹配除了换行符之外的任何通配符。

import re
re.search(r'.','I love FishC.com!')
<re.Match object; span=(0, 1), match='I'>

3.反斜杠

在正则表达式中,反斜杠可以剥夺元字符的特殊能力。

import re
re.search(r'\.','I love FishC.com!')
<re.Match object; span=(12, 13), match='.'>

如果想要匹配数字,可以使用(\d)。

import re
re.search(r'\d','I love 123 FishC.com!')
<re.Match object; span=(7, 8), match='1'>

4.字符类

import re
re.search(r'[aeiou]','I love 123 FishC.com!')
<re.Match object; span=(3, 4), match='o'>
import re
re.search(r'[aeiouAEIOU]','I love 123 FishC.com!')
<re.Match object; span=(0, 1), match='I'>

5.重复匹配

mport re
re.search(r'ab{3}c','abbbc')
<re.Match object; span=(0, 5), match='abbbc'>

6.元字符

(1)元字符:

.     ^    $    *    +    ?    { }    [ ]    \    |    ()
import re
re.search(r"Fish(C|D)","FishC")
<re.Match object; span=(0, 5), match='FishC'>
import re
re.search(r'^FishC','I love FishC.com!')
re.search(r'^FishC','FishC.com!')
<re.Match object; span=(0, 5), match='FishC'>
import re
re.search(r'FishC$','FishC.com!')
re.search(r'FishC$','love FishC')
<re.Match object; span=(5, 10), match='FishC'>

(2)字符串的意思:
a.小横杆(-),用来表示范围:

import re
re.findall(r"[a-z]","FishC.com")
['i', 's', 'h', 'c', 'o', 'm']

b.反斜杠(),用于字符串转义:

import re
re.search(r"[\n]","FishC.com\n")
<re.Match object; span=(9, 10), match='\n'>

c.脱字符(^),用于表示取反的意思:

import re
re.findall(r"[^a-z]","FishC.com")
['F', 'C', '.']

d.大括号({}),用来做反复的事情:

import re
re.search(r"FishC{3}","FishCCC.com")
<re.Match object; span=(0, 7), match='FishCCC'>

7.反斜杠+普通字母=特殊含义

import re
re.findall(r'\bFishC\b','FishC.com!FishC_com!FishC(FishC)')
['FishC', 'FishC', 'FishC']

8.编译正则表达式

使用re.compile()方法来进行编译:

p=re.compile("[A-Z]")
p.search("I love FishC.com!")
<re.Match object; span=(0, 1), match='I'>

9.实用的方法

使用group()才可以获得匹配的字符串:

result=re.search(r" (\w+) (\w+)","I love FishC.com!")
result
<re.Match object; span=(1, 12), match=' love FishC'>
result.group()
' love FishC'

四.第二次考核题

一.基础题
1、Python 类中包含一个特殊的变量(A),它表示当前对象自身,可以访问类的成员
A. self B. me C.this D.与类同名

2、构造方法的作用是(C)。
A.一般成员方法 B.类的初始化C.对象的初始化 D.对象的建立

3、下列代码中会输入什么(D)
try:
str1 = input().split()
for i in str1:
s.append(i)
print(“A”)
except:
print(“B”)
else:
print(“C”)
finally:
print(“D”)
A:A,B,C,D
B:C,D
C:A,C,D
D:B,D
4、 列表表达式的语法格式下
[表达式 for 迭代变量 in 可迭代对象 [if 条件表达式] ]
用列表表达式生成200以内是2的倍数或者是5的倍数的列表

[i for i in range(201) if i%2 == 0 or i%5 == 0]

5、字典 dict1={‘num’: ‘123456’, ‘name’: ‘kelvin’, ‘age’: 18}
遍历字典中所有的键值对 写出相应的代码

dict1={'num': '123456', 'name': 'kelvin', 'age': 18}
for i,j in dict1.items():
    print(i,j)

二.算法题
(1)加一

digits=[2,3,9]
def OnePlus(digits):
   s=''
   for i in digits:
        s=s+str(i)
   i=int(s)+1
   s1=str(i)
   l=[]
   for j in s1:
       l.append(int(j))
   return l
print(OnePlus(digits))

(2)装置矩阵

a=[[1,2,3,4],[2,3,4,5],[3,4,5,6]]
print("转置前")
for i in a:
    for j in i:
        print(j,end=' ')
    print()
a_copy=[[],[],[],[]]
def transpose(a):
    for i in range(len(a[0])):
        for j in range(len(a)):
            a_copy[i].append(a[j][i])
    return a_copy
l=transpose(a)
print("转置后")
for i in l:
    for j in i:
        print(j,end=' ')
    print()

(3)唱歌比赛

ns=input().split()
n=int(ns[0])
m=int(ns[1])
scores=[]
for i in range(n):
    list1=input().split()
    list2=[int(i) for i in list1]
    list2.remove(max(list2))
    list2.remove(min(list2))
    scores.append(sum(list2)/(m-2))
print(format(max(scores),'.2f'))

三.面向对象

class Book:
    def __init__(self,name,publisher):
        self.__name=name
        self.__publisher=publisher
    def getter(self):
        return self.__name
    def setter(self,name):
        self.__name=name
    def equals(self,other):
        return self.__name==name and self.__publisher==publisher
    def toString(self):
        return f'书名:{self.__name},出版社:{self.__publisher}'
class CollectionBook(Book):
    def __init__(self,name,publisher,bNo,stacks,isBorrow):
        super().__init__(name,publisher)
        self.__bNo=bNo
        self.__stacks=stacks
        self.__isBorrow=isBorrow
    def borrow(self):
        if self.__isBorrow:
            print("对不起,该书已被借")
        else:
            print("借阅成功")
            self.__isBorrow=True
    def revert(self):
        if self.__isBorrow:
            print("还书成功")
        else:
            print("该书已归还")
            self.__isBorrow=False
if __name__=='__main__':
    book1=CollectionBook(name="我不喜欢这个世界我只喜欢你",publisher="清华出版社",bNo="121",stacks="名人传",isBorrow=True)
    book2= CollectionBook(name="我不喜欢这个世界我只喜欢你",publisher="清华出版社",bNo="121",stacks="名人传",isBorrow=True)
    n=input()
    if n=='0':
        book2.borrow()
    elif n=='1':
        book2.revert()

五.第二次考核总结

这一次考核真的是做的一塌糊涂,选择题写不对,算法题不会写,简直好像就是噩梦。我觉得说白了还是因为,我基础掌握的不够牢固,平时一些书上的内容都没有记住,也不太喜欢看视频,所以导致我以17分的成绩收场。其实,很多人当面对这样的失败,挫折时总是会说,我觉得我不适合这个之类的话。但我觉得我之所以考的差并不是因为我不适合python这个方向,最重要的原因就是我并没有用心去学习,也没有把它真正的放在心上,对于一些不明白的知识点,也就是得过且过。我认为在接下来的一段时间里,我要适当地去调整自己的心态,把学习python当成一件重要的事情,不能只是看看书,不记任何东西,而是应该结合书与视频,去认真学习一些知识点,不要求多但一定要记住。对于学长发的一些练习题,也不能只是上网去搜搜答案,复制粘贴下来,要自己把它们敲下来,多敲几遍,理解它的意思,并且记住它。最后,也是最重要的就是我要合理安排我的时间,虽然我平时比较忙,但我也应该多抽一些时间呆在小组,减少请假的次数,做到学有所思,学有所获,学有所得。
我相信只要我努力一定会得到回应,我也相信如果我能留在小组跟着学长一起学习,明年的今天我也能成为别人的榜样,帮助新的同学学习python。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值