Python学习笔记

说明:

本文基本囊括了Python入门的知识点,可作为字典使用.

使用指南:

ctrl+f搜索对应知识点即可

―写于2122.4.29

正文

# #异常处理
#
# # try,except,finally
# try:
#     num1 = 7
#     num2 = 0
#     print(num1 / num2)
#     print("计算完毕")
# except (ValueError, TypeError):#对程序抛出的异常进行判断(如果有的话)
#     print("ValueError or TypeError occurred")
# except ZeroDivisionError:
#     print("一个除以0的错误")
# except:
#     print("发生了一个错误")
# finally:#一定会被执行
#     print("END")
#
# #用raise语句手动抛出异常
# raise ZeroDivisionError
# #给出异常的详细信息
# raise NameError("Invalid name!")
# #单独使用抛出当前异常需要在try/except里
# try:
#     print(1)
# except:
#     raise
#
# #Assertions断点
# #如果判断表达式为假则抛出异常AssertionError
# assert 1+1==2
# #可以在assert语句后加上异常信息
# assert 1+2==2,"算错了"
#
# #文件操作
#
# #打开文件
# # 默认以只读的形式打开文件
# myfile = open("filename.txt")
# #写入模式
# myfile = open("filename.txt", "w")
# #只读模式
# myfile = open("filename.txt", "r")
# #二进制写入模式
# myfile = open("filename.txt", "wb")
#
# #读取文件
# myfile = open("filename.txt", "r")
# cont = myfile.read()
# print(cont)
# myfile.close()
#
# #行读取文件
# #以for循环形式遍历文件
# file = open("filename.txt", "r")
# for line in file:
#     print(line)
# file.close()
# #用readline方式读取文件,一次读取一行
# file = open("filename.txt", "r")
# print(file.readline());
# file.close()
#
# #写入文件,如果这个文件不存在,则创建一个,以写入形式打开文件会删除文件原内容
# file = open("newfile.txt","w")
# file.write("写入字符串在文件里")
# file.close()
#
# file = open("newfile.txt","r")
# print(file.read())
# file.close()
#
# #write函数返回写入字节数
# msg = "Hello world!"
# file = open("newfile.txt","w")
# amount_written = file.write(msg)
# print(amount_written)
# file.close()
#
# #关闭文件
# myfile.close()
#
# #使用文件确保文件关闭
# #使用try
# try:
#     f = open("filename.txt")
#     print(f.read)
# finally:
#     f.close()
# #使用with语句
# with open("filename.txt") as f:
#     print(f.read())
#
#
# #更多类型
#
# #None 空
#
# #lambda函数
# #命名函数
# def polynomial(x):
#     return x ** 2 + 5 * x + 4
# print(polynomial(-4))
# #lambda
# print((lambda x: x**2 + 5*x + 4) (-4))
#
# #字典(map)
# ages = {
#     "Dave": 24, "Mary": 42, "John": 58
# }
# print(ages["Dave"])
# print(ages["Mary"])
# #判断一个键是否在字典中出现过
# nums = {
#     1: "one",
#     2: "two",
#     3: "three"
# }
# print(1 in nums)
# print(4 in nums)
# #get,如果在字典中找不到键值返回第二个参数当默认值
# pairs = {
#     1: "apple",
#     "orange": [2,3,4],
#     True:False,
#     None:"True"
# }
# print(pairs.get(12345,"不在字典中"))
#
# #元组tuple,与列表相似,但不能被改变
# words = ("span", "eggs", "sausages")
# #也可以不使用括号创建
# words = "span", "eggs", "sausages"
#
# #列表切片
# squares = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# print(squares[2:6])
# print(squares[3:8])
# #可以指定步长(第三个参数)
# print(squares[3:8:2])
# #反向切片
# print(squares[::-1])
# #通过公式推导列表
# cubes = [i**3 for i in range(5)]
# print(cubes)
# # 可以用if控制列表中的值
# evens = [i**2 for i in range(10) if i**2 % 2 ==0]
# print(evens)
#
# #有用的函数
#
# #字符串函数
# #字符串格式化
# nums = [4,5,6]
# msg = "Numbers:: {0} {1} {2}".format(nums[0],nums[1],nums[2])
# print(msg)
# #用命名参数赋值
# a = "{x}, {y}".format(x = 5, y =12)
# print(a)
#
# #字符串函数
# #join 将第一个字符串作为第二个字符串列表的分格
# print(", ".join(["spam", "eggs", "ham"]))
# #replace-替换另一个字符串中的一个子字符串
# print("Hello ME".replace("ME","world"))
# #startswith/endwith 分别确定字符串的开始和结束是否有子字符串
# print("This is a sentence.".startswith("This"))
# print("This is a sentence.".endswith("sentence."))
# #改变字母大小写
# #upper 大写
# print("This is a sentence.".upper())
# #lower 小写
# print("This is a sentence.".lower())
# #split 从字符串中分离出列表
# print("spam, eggs, ham".split(", "))
#
# #数值函数
# print(min(1,2,3,4,5,4,5))
# print(max(1,2,3,4,5,4,5))
# print(abs(-99))
# print(sum([1,2,3,4,5]))
#
# #列表函数
# nums = [55, 44, 33, 22, 11]
# #all和any都以列表作为参数
# if all([i > 5 for i in nums]):
#     print("All larger than 5")
# if any([i % 2 ==0 for i in nums]):
#     print("At least one is even")
# #enumerate 遍历列表的值和索引
# for v in enumerate(nums):
#     print(v)
#
# #文本分析器 查找每个字符占用的文本百分比
# def count_char(text,char):
#     count = 0
#     for c in text:
#         if c==char:
#             count += 1
#     return count
#
# filename = "newfile.txt"
# with open(filename) as f:
#     text = f.read()
# for char in "abcdefghijklmnopqrstuvwxyz":
#     perc = 100 * count_char(text,char) / len(text)
#     print("{0} - {1}%".format(char,round(perc,2)))
#
#
# #函数编程
#
# #纯函数不改变原参数值
#
# #lambda函数
# #命名函数
# def polynomial(x):
#     return x ** 2 + 5 * x + 4
# print(polynomial(-4))
# #lambda
# print((lambda x: x**2 + 5*x + 4) (-4))
#
# #map-映射函数
# def add_five(x):
#     return x + 5
# nums = [11, 22, 33, 44, 55]
# result = list(map(add_five,nums))
# print(result)
#
# #filter 函数过滤器,删除与条件不匹配的项
# nums = {11, 22, 33, 44, 55}
# res = list(filter(lambda x: x % 2 ==0,nums))
# print(res)
#
# #Generatorsd 生成器
# def countdown():
#     i=5
#     while i > 0:
#         #定义一个生成器,在不破坏局部变量的情况下箱调用方法提供结果
#         #在不结束函数的条件下返回值给调用方
#         yield i
#         i -= 1
# for i in countdown():
#     print(i)
# #将生成器转化为列表
# def numbers(x):
#     for i in range(x):
#         if i % 2 == 0:
#             yield i
# print(list(numbers(11)))
#
# #装饰器Decorators 用于在不修改原函数的情况下扩展原函数
# #方法一
# def decor(func):
#     def wrap():
#         print("==========")
#         func()
#         print("==========")
#     return wrap
# def print_text():
#     print("Hello world!")
# decorated = decor(print_text)
# decorated()
#
# #方法二
# @decor
# def print_text():
#     print("Hello world!")
# print_text()
#
# #递归
# def factorial(x):
#     if x==1:
#         return 1
#     else:
#         return x * factorial(x-1)
# print(factorial(5))
#
# #sets集合
# nums = {1, 2, 1, 3, 1, 4, 5, 6}
# print(nums)
# nums.add(-7)
# nums.remove(3)
# print(nums)
#
# #集合的数学运算
# first = {1, 2, 3, 4, 5, 6}
# second = {4, 5, 6, 7, 8, 9}
# #联合运算符| 组合成新的集合
# print(first | second)
# #交集运算符& 取公共元素
# print(first & second)
# #差分运算符- 从第一个集合中获取不相交的元素
# print(first - second)
# print(second - first)
# #对称差分算子^ 获取不相交元素
# print(first ^ second)
#
# #迭代器
# from itertools import count
#
# for i in count(3):
#     print(i)
#     if i>=11:
#         break
# #iertools 迭代工具
# from itertools import accumulate,takewhile
#
# nums = list(accumulate(range(8)))
# print(nums)
# print(list(takewhile(lambda x: x<=6,nums)))
#
#
# #面向对象编程
#
# #class类
# class Cat:
#     def __init__(self, color, legs):
#         self.color = color
#         self.legs = legs
#     def bark(self):
#         print("Woof!")
# felix = Cat("蛋黄", 4)
# rover = Cat("绿色", 4)
# stumpy = Cat("棕色", 3)
#
# #继承
# class Animal:
#     def __init__(self, name, color):
#         self.name = name
#         self.color = color
#
# class Cat(Animal):
#     def purr(self):
#         print("咕噜咕噜...")
#
# fica = Cat("Fica", "棕色")
# print(fica.color)
# fica.purr()
#
# #super() 子类函数与父类同名情况下,调用父类函数
# class A:
#     def spam(self):
#         print(1)
#
# class B(A):
#     def spam(self):
#         print(2)
#         super().spam()
#
# B().spam()
#
# #魔术方法
# #实现加号重载
# class Vector2D:
#     def __init__(self,x,y):
#         self.x = x
#         self.y = y
#     def __add__(self, other):
#         return Vector2D(self.x + other.x,self.y + other.y)
#
# first = Vector2D(5, 7)
# second = Vector2D(3,9)
# result = first + second
# print(result.x)
# print(result.y)
#
# #更多魔术方法
# '''
# -  __sub__
# *  __mul__
# /  __truediv__
# // __floordiv__
# %  __mod__
# ** __pow__
# &  __and__
# ^  __xor__
# |  __or__
#
# <  __lt__
# <= __le__
# == __eq__
# != __ne__
# >  __gt__
# >= __ge__
#
# len()     _len__
# 为i查找    __getitem__
# 为元素赋值  __setitem__
# 删除元素    __delitem__
# 为对象上迭代 __iter__
# in         __contains__
# 实现形式:
#     x + y -> x.__add__(y)
# '''
#
# #封装
#
# #弱封装 单个下划线
# #实现队列
# class Queue:
#     def __init__(self,contents):
#         self._hiddenlist = list(contents)
#
#     def push(self,value):
#         self._hiddenlist.insert(0, value)
#
#     def pop(self):
#         return self._hiddenlist.pop(-1)
#
#     def __repr__(self):
#         return "Queue({})".format(self._hiddenlist)
#
# queue = Queue([1,2,3])
# print(queue)
# queue.push(0)
# print(queue)
# queue.pop()
# print(queue)
# print(queue._hiddenlist)
#
# #强封装 双下划线
# class Spam:
#     __egg = 7
#     def print_egg(self):
#         print(self.__egg)
#
# s = Spam()
# s.print_egg()
# #可以这样访问
# print(s._Spam__egg)
# #下面不行
# #print(s.__egg)
#
# #静态方法
# class Rectangle:
#     def __init__(self, width, height):
#         self.width = width
#         self.height = height
#
#     def calculate_area(self):
#         return self.width * self.height
#
#     @classmethod
#     def new_square(cls, side_length):
#         return cls(side_length, side_length)
#
# square = Rectangle.new_square(5)
# print(square.calculate_area())
#
# #属性 使属性只读
# class Pizza:
#     def __init__(self, toppings):
#         self.toppings = toppings
#
#     @property
#     def pineapple_allowed(self):
#         return False
#
# pizza = Pizza(["cheese", "tomato"])
# print(pizza.pineapple_allowed)
# #不能改
# #pizza.pineapple_allowed = True
#
# #Properties
# class Pizza:
#     def __init__(self, toppings):
#         self.toppings = toppings
#         self._pineapple_allowed = False
#
#     @property
#     def pineapple_allowed(self):
#         return self._pineapple_allowed
#
#     @pineapple_allowed.setter
#     def pineapple_allowed(self, value):
#         if value:
#             password = input("Enter the password: ")
#             if password == "Sw0rdf1sh!":
#                 self._pineapple_allowed = value
#             else:
#                 raise ValueError("Alert! Intruder!")
#
#
# pizza = Pizza(["cheese", "tomato"])
# print(pizza.pineapple_allowed)
# pizza.pineapple_allowed = True
# print(pizza.pineapple_allowed)
#
# #正则表达式
# import re
# #字符串匹配
# pattern = r"spam"
# #match 确定开头是否匹配
# if re.match(pattern,"samspam"):
#     print("匹配")
# else:
#     print("不匹配")
# #search 找模式串匹配
# if re.search(pattern,"samspam"):
#     print("匹配")
# else:
#     print("不匹配")
# #findall 返回所有匹配字串列表
# if re.findall(pattern,"samspam"):
#     print("匹配")
# else:
#     print("不匹配")
#
# #正则表达式的返回
# pattern = r"pam"
#
# match = re.search(pattern,"eggspamsausage")
# if match:
#     print(match.group())
#     print(match.start())
#     print(match.end())
#     print(match.span())
#
# #Search&Replace sub函数,替换所有匹配内容,返回修改后字符串
# str = "My name is David . Hi David."
# pattern = r"David"
# newstr = re.sub(pattern, "Amy", str)
# print(newstr)
#
# #模式字符
# '''
# ^           匹配字符串的开头
# $           匹配字符串的末尾。
# .           匹配任意字符,除了换行符,当re.DOTALL标记被指定时,则可以匹配包括换行符的任意字符。
# [...]       用来表示一组字符,单独列出:[amk] 匹配 'a','m'或'k'
# [^...]      不在[]中的字符:[^abc] 匹配除了a,b,c之外的字符。
# re*         匹配0个或多个的表达式。
# re+         匹配1个或多个的表达式。
# re?         匹配0个或1个由前面的正则表达式定义的片段,非贪婪方式
# re{ n}      精确匹配 n 个前面表达式。例如,o{2}不能匹配 "Bob" 中的 "o",但是能匹配 "food" 中的两个 o。
# re{ n,}     匹配 n 个前面表达式。例如, o{2,} 不能匹配"Bob"中的"o",但能匹配 "foooood"中的所有 o。"
# o{1,}"      等价于 "o+"。"o{0,}" 则等价于 "o*"。
# re{ n, m}   匹配 n 到 m 次由前面的正则表达式定义的片段,贪婪方式
# a| b        匹配a或b(re)对正则表达式分组并记住匹配的文本
# (?imx)      正则表达式包含三种可选标志:i, m, 或 x 。只影响括号中的区域。
# (?-imx)     正则表达式关闭 i, m, 或 x 可选标志。只影响括号中的区域。
# (?: re)     类似 (...), 但是不表示一个组(?imx: re)在括号中使用i, m, 或 x 可选标志
# (?-imx: re) 在括号中不使用i, m, 或 x 可选标志
# (?#...)     注释.
# (?= re)     前向肯定界定符。如果所含正则表达式,以 ... 表示,在当前位置成功匹配时成功,否则失败。但一旦所含表达式已经尝试,匹配引擎根本没有提高;模式的剩余部分还要尝试界定符的右边。
# (?! re)     前向否定界定符。与肯定界定符相反;当所含表达式不能在字符串当前位置匹配时成功
# (?> re)     匹配的独立模式,省去回溯。
# w           匹配字母数字及下划线
# W           匹配非字母数字及下划线
# s           匹配任意空白字符,等价于 [ ].
# S           匹配任意非空字符
# d           匹配任意数字,等价于 [0-9].
# D           匹配任意非数字
# A           匹配字符串开始
# Z           匹配字符串结束,如果是存在换行,只匹配到换行前的结束字符串。
# z           匹配字符串结束
# G           匹配最后匹配完成的位置。匹配一个单词边界,也就是指单词和空格间的位置。例如, 'er' 可以匹配"never" 中的 'er',但不能匹配 "verb" 中的 'er'。
# B           匹配非单词边界。'erB' 能匹配 "verb" 中的 'er',但不能匹配 "never" 中的 'er'。,, 等.匹配一个换行符。匹配一个制表符。等
# ...9        匹配第n个分组的内容。匹配第n个分组的内容,如果它经匹配。否则指的是八进制字符码的表达式。
# +           一个或多个重复
# ?           零或一次重复
# {}          重复次数
# '''
#
# #组
# pattern = r"egg(spam)*"
# if re.match(pattern, "egg"):
#     print("Match 1")
# if re.match(pattern, "eggspamspamspamegg"):
#     print("Match 2")
# if re.match(pattern, "spam"):
#     print("Match 3")
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值