Python语言及应用:学习笔记(2)

4Python模块、包、程序

    模块,包为Python更大的代码结构,之前的函数,判段循环语句等类似段落,而模块,包类似文章。

4.1模块

示例:

#Python模块
#命令行参数
import sys
print(sys.argv)
#在命令行可以直接执行文件
#python part2.py  arg1 arg2

#模块
#导入模块
import random
#导入模块,设置别名
import  random as ran
#部分导入模块
from random import choice
#部分导入模块,设置别名
from random import  choice as choS

#模块搜索路径
#返回python模块搜索路径,优先级从上到下
#如果在列表路径之前定义和python提供模块同名,那么不会调用python同名模块,调用自己模块
for place in sys.path:
    print(place)

4.2包

    创建Python包,类似于文件,其中需要__init__.py文件。

示例:main.py

#包
#创建program文件夹,创建sources包
#在program创建main.py,主模块
#在sources创建daily.py,weekly.py,还有__init_.py,区分文件夹和包
#导入下级目录模块
from program.sources import daily
from program.sources import  weekly

#调用模块函数
daily.get_daily_info()
weekly.get_weekly_info()

示例:weekly.py

def get_weekly_info():
    print('this is weekly info')

示例:daily.py

def get_daily_info():
    print('this is daily info')

4.3Python标准库

    Python提供许多有用的模块。

示例1:字典缺失值

#Python标准库
#1处理缺失值
dict1 = {'tom':11,'kai':22}
print(dict1)
#setdefault(),如果键值不存在,插入字典,返回插入键值
#setdefault(),如果键值存在,不会修改键值,返回原键值
ret = dict1.setdefault('ken',44)
#返回被插入值
print(ret)
print(dict1)
ret = dict1.setdefault('ken',30)
print(ret)
print(dict1)

#设置字典默认值
from collections import defaultdict
#建立,具有默认键值字典
#如果不指定值,默认为[]
dict1 = defaultdict(list)
#如果不指定值,默认为0
dict2 = defaultdict(int)
#如果不指定值,默认为{}
dict3 = defaultdict(dict)
dict1['a'] = 1
dict1['b']
dict2['a']
dict3['a']
print(dict1)
print(dict2)
print(dict3)

示例2:Counter计数器

#使用counter计数器
from collections import Counter
list1 = ["hello","world","welcome","hello"]
list1_count = Counter(list1)
print(list1_count)
#降序返回所有元素,元组列表
print(list1_count.most_common())
#counter计数器加减
list2 = ["hi","world","word","hi"]
list2_count = Counter(list2)
#组合计数器
#Counter({'hello': 2, 'world': 2, 'hi': 2, 'welcome': 1, 'word': 1})
print(list1_count + list2_count)
#count2中减去count1共同存在元素
#Counter({'hi': 2, 'word': 1})
print(list2_count - list1_count)
#count2,count1中共同存在元素,求交集
#Counter({'world': 1})
print(list2_count & list1_count)
#count2,count1中所有元素,求并集,+类似,但是没有将计数相加,只取最大值
#Counter({'hi': 2, 'hello': 2, 'world': 1, 'word': 1, 'welcome': 1})
print(list2_count | list1_count)

示例3:使用有序字典OrderedDict()按键排序

#有序字典
from collections import OrderedDict
#元组构建有序字典
dict1 = OrderedDict([("2","hello"),("1","world"),("3","well")])
for dict_item in dict1:
    print(dict_item)

示例4:双端队列:栈+队列

#双端队列
#判断是否是回文
def judge_huiwen(word):
    from collections import  deque
    dq = deque(word)
    while len(dq) > 1:
        if dq.pop() != dq.popleft():
            return  False
    return  True
print(judge_huiwen('a'))
print(judge_huiwen('abccba'))
print(judge_huiwen('abcca'))
#字符串反转
str1 = 'abccba'
str2 = str1[::-1]
print(str1,str2)

示例5:使用itertools迭代结构

#迭代器
import itertools
#chain的参数迭代对象
# for iter_item in itertools.chain([1,2],[3,4]):
#     print(iter_item)
#cycle返回无限迭代器
# for iter_item in itertools.cycle([1,2]):
#     print(iter_item)
#accumulate计算累加和
for iter_item in itertools.accumulate([1,2,3,4,5]):
    print(iter_item)
#可以把函数作为第二个参数,代替默认加法
def multipy(a,b):
    return a * b
for iter_item in itertools.accumulate([1,2,3,4,5],multipy):
    print(iter_item)

示例6:pprint输出

#pprint
from pprint import pprint
dict1 = {"1":"hello","2":"world","3":"well"}
pprint(dict1)

更多Python代码

PyPI · The Python Package Index

5Python对象和类

    Python所有数据都是以对象形式存在。

    对象包含数据attribute,也包含动作function,方法。

5.1定义类

#对象和类
#创建类
#空类
class Person():
    pass
#定义类初始化方法
class Person():
    def __init__(self,name):
        self.name = name
#创建对象
person1 = Person('tom')

#类继承
#从已有类添加修改部分功能
#Doctor类继承Person
class Doctor(Person):
    #子类重写父类方法
    def __init__(self,name):
        self.name = 'doctor:' + name
    #子类添加新方法
    def doctor_say(self):
        print(self.name + " is a doctor")

doctor1 = Doctor("tom")
print(doctor1.name)
doctor1.doctor_say()

#使用super使用父类方法
class Worker(Person):
    #子类重写初始化方法后,父类初始化方法不会再调用
    #需要使用super显式调用
    def __init__(self,name,age):
        super.__init__(name)
        self.age = 10


#self调用机制
#查找worker1对象对应类Worker
#将worker1作为参数传入Worker类的worker_say方法
worker1 = Worker("tom",10)
worker1.worker_say()
#相同效果
worker1 = Worker("tom",10)
Worker.worker_say(worker1)

5.2属性get,set方法

#属性get,set方法
class Duck():
    def __init__(self,name):
        self.in_name = name
    #get方法
    @property
    def name(self):
        return  self.in_name
    #set方法
    @name.setter
    def name(self,name):
        self.in_name = name
duck1 = Duck("tom")
duck1.name = "Sim"

#使用in_name修改为__name,隐藏访问
class Duck():
    def __init__(self,name):
        self.__name = name
    #get方法
    @property
    def name(self):
        return  self.__name
    #set方法
    @name.setter
    def name(self,name):
        self.__name = name
duck1 = Duck("tom")
#这样无法外部访问
#因为__name已经修改为_Duck__name
print(duck1.__name)

5.3方法类型

#类方法
class Duck():
    #类属性
    #类创建次数
    count = 0
    def __init__(self,name):
        self.name = name
        Duck.count += 1
    #类方法
    @classmethod
    def cls_count(cls):
        print(cls.count)
    #静态方法
    @staticmethod
    def sta_method():
        print("this is static method")
duck1 = Duck("Tom")
Duck.cls_count()
Duck.sta_method()

5.4多态

示例:

#多态
#鸭子类型
class Say():
    def __init__(self,says):
        self.say = says
    def say_something(self):
        return self.say
class Say_1(Say):
    def say_something(self):
        return self.say + 'say 1'
class Say_2():
    def __init__(self,says):
        self.say = says
    def say_something(self):
        return self.say + 'say 2'
#鸭子类型
#像鸭子一样走路,像鸭子一样叫就是鸭子
def duck_type(obj):
    print(obj.say_something())
say = Say('Tom say')
say1 = Say_1('Lu say')
say2 = Say_2('no say')
duck_type(say)
duck_type(say1)
duck_type(say2)

5.5特殊方法

    比较的魔术方法:

__eq__(self,other) self == other

__ne__(self,other) self != other

__lt__(self,other) self < other

__gt__(self,other) self > other

__le__(self,other) self <= other

__ge__(self,other) self >= other

    算术的魔术方法:

__add__(self,other) self + other

__sub__(self,other) self – other

__mul__(self,other) self * other

__floordiv__(self,other) self // other

__truediv__(self,other) self / other

__mod__(self,other) self % other

__pow__(self,other) self ** other

   

    其他魔术方法

__str__(self) str(self)

__repr__(self) repr(self)

__len__(self) len(self)

示例:

#魔术方法
class Word():
    def __init__(self,words):
        self.word = words
    #重写类的eq方法
    def __eq__(self,others):
        return self.word.lower() == others.word.lower()
words1 = Word('HA')
words2 = Word('ha')
print(words1 == words2)

5.6组合

    像变形金刚一样,有的类属性由一个一个部件组合而成。

示例:

#组合

class Header:

    def __init__(self,desc):

        self.desc = desc

class Body:

    def __init__(self,desc):

        self.desc = desc

class Translater():

    def __init__(self,header,body):

        self.header = header

        self.body = body

    def about(self):

        print("header:",self.header.desc,"body:",self.body.desc)

header1 = Header("big")

body1 = Body("tall")

translater1 = Translater(header1,body1)

translater1.about()

5.7命名元组

示例:

#命名元组

from collections import namedtuple

#创建命名元组

Translater1 = namedtuple("Translater1","header body")

#元组赋值

translater1 = Translater1("big","tall")

print(translater1)

print(translater1.header)

#使用字典创建

dict1 = {"header":"small","body":"short"}

translater2 = Translater1(**dict1)

print(translater2)

#替换命名元组属性值

translater3 = translater2._replace(header="middle",body="tall")

print(translater3)

6Python数据处理

    计算机基本存储单元字节,一个字节8位。可以表示256种不同字符。

    ASCII只使用7位,可以表式128中字符。

    Unicode通用字符集,Unicode 15.1 Character Code Charts

6.1编码解码

示例:

#unicode
import unicodedata
def unicode_info(value):
    #字符标准名
    name = unicodedata.name(value)
    #通过标准名,返回Unicode字符
    p_value = unicodedata.lookup(name)
    print("value =",value,"name =",name,"print value:",p_value)

#\u后面四个十六进制数字,00-FF指定平面,00表示ASCII字符集
#\U后面8个十六进制数字,最左位为0
#\N{name},name为字符标准名
unicode_info("A")
unicode_info("\u0030")
code_e =  "\N{LATIN SMALL LETTER E WITH DIAERESIS}"
print(code_e)
code_cafe = "caf\u00e9"
print(code_cafe)

#使用UTF-8编码解码
#字符串处理1.将字符串编码为字节;2.将字节解码为字符串;
#编码encode(),将字符串转换为字节
#'ascii',ASCII编码
#‘utf-8',8位变长编码
#'latin-1',ISO 8859-1
#'cp-1252',windows常用编码
#'unicode-escape',Unicode转义文本
snowman = '\u2603'
#使用len,unicode字符串长度
print(len(snowman))
#将unicode字符串,编码位utf-8
code_utf = snowman.encode('utf-8')
#这里len返回字节数
print(len(code_utf))
#可以使用其他编码方式,但是保证该编码支持该字符
str1 = '\U1039'
#第二个参数ignore:忽略无法转换字符;replace:无法转换字符替换为?
#backslashreplace:创建unicode-escape类似Unicode字符串
#xmlcharrefreplace:创建网页使用字符串
code_error = str1.encode('ascii','ignore')

#解码
#将字节序列转换为字符串
#使用decode解码
str1 = code_utf.decode("utf-8")

6.2格式化

    Python输出字符串格式化。

示例:

#格式化
#1.string % data
#%s 字符串
#%d 十进制整数
#%x 十六进制整数
#%o 八进制整数
#%f 十进制浮点数
#%e 科学计数法浮点数
#%g 十进制或科学计数法表示浮点数
#%% 文本值本身
data1 = '1.333'
print('%s' % data1)
data1 = 12
print('%d' % data1)
data1 = 12
print('%x' % data1)
data1 = 12
print('%o' % data1)
data1 = 1.333
print('%f' % data1)
print('%e' % data1)
data1 = 100
print('%d%%' % data1)

data1 = 10
data2 = 1.44
data3 = "hello"
print("%d %f %s" % (data1,data2,data3))
#指定最小宽度,右对齐
print("%10d %10f %10s" % (data1,data2,data3))
#左对齐
print("%-10d %-10f %-10s" % (data1,data2,data3))
#指定最大宽度,当为浮点数f时指定的小数位数
print("%-10.2d %-10.2f %-10.2s" % (data1,data2,data3))
#将设定参数化
print("%*.*f" % (10,5,data2))

#新格式化
#使用'{}{}{}'.format(n,f,s)
print("{}{}{}".format(data1,data2,data3))
#指定顺序
#0代表第一参数,1代表第二个参数,2代表第三个参数
print("{2}{0}{1}".format(data1,data2,data3))
#使用键值方式
print("{key1}{key2}{key3}".format(key1 = 10,key2 = 1.33,key3 = "hello"))
dict1 = {"key1":1.33,"key2":"words"}
print("{0[key1]}{0[key2]}{1}".format(dict1,"world"))
#设定格式
print("{0:d}{1:f}{2:s}".format(10,2.33,"welcome"))
#>左对齐,<右对齐,^居中
print("{key1:>10.4f}{key2:<10.5f}{key3:^10.2f}"\
    .format(key1 = 1.3313,key2 = 2.4422,key3 = 3.333432))
#填充字符******welcome*******
print("{0:*^20s}".format("welcome"))

6.3正则表达式匹配

    正则表达式匹配

示例:

#正则表达式匹配
import  re
#match 以指定pattern开头字符串
#<re.Match object; span=(0, 2), match='hi'>
result1 = re.match("hi","hi,welcome")
print(result1)
#返回匹配对象
print(result1.group())
#只能匹配pattern开头字符串
result1 = re.match("we","hi,welcome")
print(result1)
#search()返回第一次成功匹配
result1 = re.search("we","hi,welcome")
print(result1)
print(result1.group())
#findall()返回所有不重叠匹配
result1 = re.findall("n","welcome,nothing series n")
#匹配出['n', 'n', 'n']
print(result1)
#只匹配['no', 'ng'],n.表示必须两个字符,n.?表示不管n后有没有字符都匹配
result1 = re.findall("n.","welcome,nothing series n")
print(result1)
#split()根据pattern,将source切分
result1 = re.split("n.?","welcome no hi,no hello!")
#匹配的字符串会截掉,['welcome ', ' hi,', ' hello!']
print(result1)
#sub(),将所有匹配pattern,修改为replacement
result1 = re.sub("n.?","*","nowelcomeno")
print(result1)

#正则表达式规则
#.代表单一字符;*代表任意个字符;.*任意多个字符;
#特殊字符
#\d 数字字符
#\D 非数字字符
#\w 字母或数字字符
#\W 非字母数字字符
#\s 空白符
#\S 非空白符
#\b 单词边界
#\B 非单词边界
import  string
#可打印100的ASCII字符
printwords = string.printable
#匹配字母,数字,下划线
result1 = re.findall("\w",printwords)
print(result1)
#空格符
result1 = re.findall("\s",printwords)
#[' ', '\t', '\n', '\r', '\x0b', '\x0c']
print(result1)

#使用标识符
# abc 文本abc
# (expr) expr
# expr1 | expr2  expr1或expr2
# . \n以外所有字符
# ^ 源字符串开头
# $ 源字符串结尾
# prev? 0个或1个prev
# prev* 0个或多个prev
# prev*? 0个或多个prev
# prev+ 1个或多个prev
# prev+? 1个或多个prev
# prev{m} m个连续prev
# prev{m,n} m到n个prev
# prev{m,n}? m到n个prev
#[abc]  a或b或c,a|b|c
#[^abc] 非a或b或c
#prev(?=next) 如果后面为next,返回prev
#prev(?!next) 如果后面非next,返回prev
#(?<=prev)next  如果前面为prev,返回next
#(?<!prev)next  如果前面不为prev,返回next
#源字符串
source1 = "I like play baseball,I like play football,I like play game"
print(re.findall("play | ball",source1))
print(re.findall("[a-z]ame",source1))
print(re.findall(".{1,4}ball",source1))
#匹配分组
#使用match,search
result1 = re.search("(.{1,4}ball)",source1)
print(result1)
print(result1.group())
print(result1.groups())

6.4 二进制数据

示例:

#字节,字节数组
#字节是不可变的
#字节数组是可变的
list1 = [1,3,4,255]
byte_list1 = bytes(list1)
#b'\x01\x03\x04\xff'
print(byte_list1)
#字节数组
byte_array1 = bytearray(list1)
print(byte_array1)
#字节数组可变
byte_array1[1] = 200
print(byte_array1)

#struct转换字节
#字节序标识符
#< 小端方案  > 大端方案
#x  跳过一个字节
#b  有符号字节
#B  无符号字节
#h  有符号短整数
#H  无符号短整数
#i   有符号整数
#I   无符号整数
#l   有符号长整数
#L   无符号长整数
#Q   无符号long long型整数
#f  单精度浮点数
#d   双精度浮点数
#p  数量和字符
#s  字符
import struct
bit1 = struct.pack('>L', 122)
bit2 = struct.pack('<L', 122)
print(bit1,bit2)
data1 = struct.unpack('>L', bit1)
data2 = struct.unpack('<L', bit2)
print(data1,data2)
#其他二进制工具
#bitstring https://code.google.com/p/python-bitstring
#construct http://construct.readthedocs.org/en/latest/
#hachoir https://bitbucket.org/haypo/hachoir/wiki/Home
#binio http://spika.net/py/binio/

#使用binascii转换
import binascii
#二进制数据和多种字符串表示
png_header = binascii.hexlify(b'\x89PNG\r\n\x1a\n')
print(png_header)

#位运算符
# & 与
# | 或
# ^ 异或
# ~ 翻转
# << 左位移
# >> 右位移

  • 23
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

偶是不器

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值