zoukankan      html  css  js  c++  java
  • python学习之路08(正则表达式和网络)

    ---恢复内容开始---

    1.###正则表达式 - 单个字符匹配
    import re
    """
    findall 把匹配的结果直接返回到列表中
    lst=re.findall("正则表达式,","要匹配的字符串")
    """
    #预定义字符集
    #(1) d 匹配数字
    lst=re.findall("d","UIUI uiui8980(*(*神秘男孩xboy!))")
    print(lst) #['8', '9', '8', '0']

    #(2) D 匹配非数字
    lst=re.findall("D","UIUI uiui8980(*(*神秘男孩xboy!))")
    print(lst) #['U', 'I', 'U', 'I', ' ', 'u', 'i', 'u', 'i', '(', '*', '(', '*', '神', '秘', '男', '孩', 'x', 'b', 'o', 'y', '!', ')', ')']

    #(3) w 匹配字母或数字或者下划线
    lst=re.findall("w","UIUI uiui!@#¥¥%¥%&*8980(*(*神秘男孩xboy!))")
    print(lst) #['U', 'I', 'U', 'I', 'u', 'i', 'u', 'i', '8', '9', '8', '0', '神', '秘', '男', '孩', 'x', 'b', 'o', 'y']

    #(4) W 匹配非字母或数字或者下划线
    lst=re.findall("W","UIUI uiui!@#¥¥%¥%&*8980(*(*神秘男孩xboy!))")
    print(lst) #[' ', '!', '@', '#', '¥', '¥', '%', '¥', '%', '&', '*', '(', '*', '(', '*', '!', ')', ')']

    #(5) s 匹配任意空白符
    lst=re.findall("s","123 789")
    print(lst) #[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']

    #(6) S 匹配任意非空白符
    lst=re.findall("S","123 456")
    print(lst) #['1', '2', '3', '4', '5', '6']

    #(7) 匹配任意换行符
    strvar="""
    本来无一物,何处惹尘埃,无住 生心
    """
    lst=re.findall(" ",strvar)
    print(lst) #[' ', ' ']

    #(8) 匹配制表符 缩进
    lst=re.findall(" ","慎吾心如意,汝意 不可信")
    print(lst) #[]

    #字符组[]
    #默认必须从字符组当中选一个
    lst=re.findall("[abc]","aaa")
    print(lst) #['a', 'a', 'a']

    lst=re.findall("[abc]","ccc")
    print(lst) #['c', 'c', 'c']

    lst=re.findall("[abc]","6767yuyan-=-=-=====")
    print(lst) #['a']

    print(re.findall('a[abc]b','aab abb acb adb')) #['aab', 'abb', 'acb']
    print(re.findall('a[0123456789]b','a1b a2b a3b acb ayb')) #['a1b', 'a2b', 'a3b']
    #优化版 0-9 从0到9当中选一个 "-"代表的是一个范围,是特殊字符
    print(re.findall('a[0-9]b','a1b a2b a3b acb ayb')) #['a1b', 'a2b', 'a3b']

    print(re.findall('a[abcdefg]b','a1b a2b a3b acb ayb adb')) #['acb', 'adb']
    #优化版 a-z代表的是26个小写字母
    print(re.findall('a[a-g]b','a1b a2b a3b acb ayb adb')) #['acb', 'adb']

    #优化版 A-Z代表的是26个大写字母
    print(re.findall('a[A-Z]b','a1b a2b a3b aAb aYb aDb')) #['aAb', 'aYb', 'aDb']

    #注意事项: 0-z不但能表示大小写字母,数字,还包含了一些特殊字符
    print(re.findall('a[0-9][*#/]b','a1/b a2b a29b a56b a456b')) #['a1/b']
    #字符组 中的 ^ 代表的是除了。。。[^-+*/]除了-+*/ 之外的所有富豪都匹配
    print(re.findall('a[^-+*/]b','a%b ccaa*bda&bd')) #['a%b', 'a&b']

    #如果就是想匹配特殊的符号,用进行转译
    #匹配^
    print(re.findall('a[^]b','a^b')) #['a^b']

    #匹配 代表退格 backspace
    lst=re.findall(r'a\b',r'a')
    print(re.findall(r'a\b',r'a')) # ['a\b']
    print(lst[0]) #a
    2.###正则表达式 - 多个字符匹配
    #量词练习
    import re
    """1) ?匹配0个或者1个a"""
    print(re.findall('a?b','abbzab abb aab')) #['ab', 'b', 'ab', 'ab', 'b', 'ab']

    """2) +匹配1个或者多个a"""
    print(re.findall('a+b','b ab aaaaab abb')) #['ab', 'aaaaab', 'ab']

    """3) *匹配0个或者多个a"""
    print(re.findall('a*b','b ab aaaaaab abbbbbbbbb')) #['b', 'ab', 'aaaaaab', 'ab', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b']

    """4) {m,n}匹配m个至n个a"""
    print(re.findall('a{1,3}b','aaab ab aab abbb aaz aabb')) #['aaab', 'ab', 'aab', 'ab', 'aab']
    #{1} 必须只有1个
    print(re.findall('a{1}b','aaab ab aab abbb aaz aabb')) #['ab', 'ab', 'ab', 'ab', 'ab']
    #{1,} 至少有1个
    print(re.findall('a{1,}b','aaab ab aab abbb aaz aabb')) #['aaab', 'ab', 'aab', 'ab', 'aab']

    #贪婪匹配和非贪婪匹配
    """
    贪婪匹配:默认向更多次匹配(回溯算法)
    非贪婪匹配:默认向更少次匹配(语法在量词的后面加"?"号)
    . 代表除了 ,可以匹配任意字符
    .? ?匹配0个或者1个
    .* *匹配0个或者多个
    .+ +匹配1个或者多个
    {m,n} {m,n}匹配m个至n个

    回溯算法:从左到右进行匹配 ,直到再也匹配不到了,回头,拿离右边最近的一个值
    非贪婪匹配语法:语法在量词的后面加"?"号
    .?? ?匹配0个
    .+? +匹配1个
    .*? *匹配0个
    .{m,n}? 向m个匹配
    """
    #(1)贪婪匹配
    strvar='刘能和刘老根儿和刘铁棍子123子456'
    lst=re.findall("刘.?",strvar)
    print(lst) #['刘能', '刘老', '刘铁']

    lst=re.findall("刘.+",strvar) #['刘能和刘老根儿和刘铁棍子123子456']
    print(lst)

    lst=re.findall("刘.*",strvar) #['刘能和刘老根儿和刘铁棍子123子456']
    print(lst)

    lst=re.findall("刘.{1,100}",strvar) #['刘能和刘老根儿和刘铁棍子123子456']
    print(lst)

    #(2)非贪婪匹配
    strvar='刘能和刘老根儿和刘铁棍子123子456'
    lst=re.findall("刘.??",strvar)
    print(lst) #['刘', '刘', '刘']

    lst=re.findall("刘.+?",strvar)
    print(lst) #['刘能', '刘老', '刘铁']

    lst=re.findall("刘.*?",strvar)
    print(lst) #['刘', '刘', '刘']

    lst=re.findall("刘.{1,100}?",strvar)
    print(lst) #['刘能', '刘老', '刘铁']
    #贪婪
    lst=re.findall("刘.*子",strvar)
    print(lst) #['刘能和刘老根儿和刘铁棍子123子']
    #非贪婪
    lst=re.findall("刘.*?子",strvar)
    print(lst) #['刘能和刘老根儿和刘铁棍子']

    ####边界符  ^ $
    """
    卡在左边界:w
    卡在右边界:d

    任何的正则表达式,字符左边都加上:r防止转译
    """
    strvar="word pwd sef"
    lst=re.findall(r"w.*",strvar)
    print(lst) #['word pwd sef']
    lst=re.findall(r".*?d",strvar)
    print(lst) #['word', ' pwd']
    lst=re.findall(r"w.*?d",strvar)
    print(lst) #['word']
    #单独匹配word
    lst=re.findall(r"wS*",strvar)
    print(lst) #['word']

    """
    ^ 必须以....开头
    $ 必须以....结尾
    无论是 ^ 还是 $ ,都需要吧字符串看成一个整体
    """
    strvar="大哥大嫂大爷"
    # print(re.findall("大.",strvar)) #['大哥', '大嫂', '大爷']
    # print(re.findall("^大.",strvar)) #['大哥']
    # print(re.findall("大.$",strvar)) #['大爷']
    # print(re.findall("^大.$",strvar)) #[]
    # print(re.findall("^大.*?$",strvar)) #['大哥大嫂大爷']
    # print(re.findall("^大.*?大$",strvar)) #[] 必须以大字开头,以爷字结尾
    print(re.findall("^大.*?爷$",strvar)) #['大哥大嫂大爷']


    # print(re.findall("^g.*? ","giveme lgfive gay")) #['giveme ']
    # print(re.findall("five$","aassfive")) #['five']
    # print(re.findall("^giveme$","giveme")) #['giveme']
    # print(re.findall("^giveme$","giveme giveme")) #[]
    # print(re.findall("giveme","giveme giveme")) #['giveme', 'giveme']
    # print(re.findall("^g.*e","giveme lgfive gay")) #['giveme lgfive']

    ---恢复内容结束---

    1.###正则表达式 - 单个字符匹配
    import re
    """
    findall 把匹配的结果直接返回到列表中
    lst=re.findall("正则表达式,","要匹配的字符串")
    """
    #预定义字符集
    #(1) d 匹配数字
    lst=re.findall("d","UIUI uiui8980(*(*神秘男孩xboy!))")
    print(lst) #['8', '9', '8', '0']

    #(2) D 匹配非数字
    lst=re.findall("D","UIUI uiui8980(*(*神秘男孩xboy!))")
    print(lst) #['U', 'I', 'U', 'I', ' ', 'u', 'i', 'u', 'i', '(', '*', '(', '*', '神', '秘', '男', '孩', 'x', 'b', 'o', 'y', '!', ')', ')']

    #(3) w 匹配字母或数字或者下划线
    lst=re.findall("w","UIUI uiui!@#¥¥%¥%&*8980(*(*神秘男孩xboy!))")
    print(lst) #['U', 'I', 'U', 'I', 'u', 'i', 'u', 'i', '8', '9', '8', '0', '神', '秘', '男', '孩', 'x', 'b', 'o', 'y']

    #(4) W 匹配非字母或数字或者下划线
    lst=re.findall("W","UIUI uiui!@#¥¥%¥%&*8980(*(*神秘男孩xboy!))")
    print(lst) #[' ', '!', '@', '#', '¥', '¥', '%', '¥', '%', '&', '*', '(', '*', '(', '*', '!', ')', ')']

    #(5) s 匹配任意空白符
    lst=re.findall("s","123 789")
    print(lst) #[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']

    #(6) S 匹配任意非空白符
    lst=re.findall("S","123 456")
    print(lst) #['1', '2', '3', '4', '5', '6']

    #(7) 匹配任意换行符
    strvar="""
    本来无一物,何处惹尘埃,无住 生心
    """
    lst=re.findall(" ",strvar)
    print(lst) #[' ', ' ']

    #(8) 匹配制表符 缩进
    lst=re.findall(" ","慎吾心如意,汝意 不可信")
    print(lst) #[]

    #字符组[]
    #默认必须从字符组当中选一个
    lst=re.findall("[abc]","aaa")
    print(lst) #['a', 'a', 'a']

    lst=re.findall("[abc]","ccc")
    print(lst) #['c', 'c', 'c']

    lst=re.findall("[abc]","6767yuyan-=-=-=====")
    print(lst) #['a']

    print(re.findall('a[abc]b','aab abb acb adb')) #['aab', 'abb', 'acb']
    print(re.findall('a[0123456789]b','a1b a2b a3b acb ayb')) #['a1b', 'a2b', 'a3b']
    #优化版 0-9 从0到9当中选一个 "-"代表的是一个范围,是特殊字符
    print(re.findall('a[0-9]b','a1b a2b a3b acb ayb')) #['a1b', 'a2b', 'a3b']

    print(re.findall('a[abcdefg]b','a1b a2b a3b acb ayb adb')) #['acb', 'adb']
    #优化版 a-z代表的是26个小写字母
    print(re.findall('a[a-g]b','a1b a2b a3b acb ayb adb')) #['acb', 'adb']

    #优化版 A-Z代表的是26个大写字母
    print(re.findall('a[A-Z]b','a1b a2b a3b aAb aYb aDb')) #['aAb', 'aYb', 'aDb']

    #注意事项: 0-z不但能表示大小写字母,数字,还包含了一些特殊字符
    print(re.findall('a[0-9][*#/]b','a1/b a2b a29b a56b a456b')) #['a1/b']
    #字符组 中的 ^ 代表的是除了。。。[^-+*/]除了-+*/ 之外的所有富豪都匹配
    print(re.findall('a[^-+*/]b','a%b ccaa*bda&bd')) #['a%b', 'a&b']

    #如果就是想匹配特殊的符号,用进行转译
    #匹配^
    print(re.findall('a[^]b','a^b')) #['a^b']

    #匹配 代表退格 backspace
    lst=re.findall(r'a\b',r'a')
    print(re.findall(r'a\b',r'a')) # ['a\b']
    print(lst[0]) #a
    2.###正则表达式 - 多个字符匹配
    #量词练习
    import re
    """1) ?匹配0个或者1个a"""
    print(re.findall('a?b','abbzab abb aab')) #['ab', 'b', 'ab', 'ab', 'b', 'ab']

    """2) +匹配1个或者多个a"""
    print(re.findall('a+b','b ab aaaaab abb')) #['ab', 'aaaaab', 'ab']

    """3) *匹配0个或者多个a"""
    print(re.findall('a*b','b ab aaaaaab abbbbbbbbb')) #['b', 'ab', 'aaaaaab', 'ab', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b']

    """4) {m,n}匹配m个至n个a"""
    print(re.findall('a{1,3}b','aaab ab aab abbb aaz aabb')) #['aaab', 'ab', 'aab', 'ab', 'aab']
    #{1} 必须只有1个
    print(re.findall('a{1}b','aaab ab aab abbb aaz aabb')) #['ab', 'ab', 'ab', 'ab', 'ab']
    #{1,} 至少有1个
    print(re.findall('a{1,}b','aaab ab aab abbb aaz aabb')) #['aaab', 'ab', 'aab', 'ab', 'aab']

    #贪婪匹配和非贪婪匹配
    """
    贪婪匹配:默认向更多次匹配(回溯算法)
    非贪婪匹配:默认向更少次匹配(语法在量词的后面加"?"号)
    . 代表除了 ,可以匹配任意字符
    .? ?匹配0个或者1个
    .* *匹配0个或者多个
    .+ +匹配1个或者多个
    {m,n} {m,n}匹配m个至n个

    回溯算法:从左到右进行匹配 ,直到再也匹配不到了,回头,拿离右边最近的一个值
    非贪婪匹配语法:语法在量词的后面加"?"号
    .?? ?匹配0个
    .+? +匹配1个
    .*? *匹配0个
    .{m,n}? 向m个匹配
    """
    #(1)贪婪匹配
    strvar='刘能和刘老根儿和刘铁棍子123子456'
    lst=re.findall("刘.?",strvar)
    print(lst) #['刘能', '刘老', '刘铁']

    lst=re.findall("刘.+",strvar) #['刘能和刘老根儿和刘铁棍子123子456']
    print(lst)

    lst=re.findall("刘.*",strvar) #['刘能和刘老根儿和刘铁棍子123子456']
    print(lst)

    lst=re.findall("刘.{1,100}",strvar) #['刘能和刘老根儿和刘铁棍子123子456']
    print(lst)

    #(2)非贪婪匹配
    strvar='刘能和刘老根儿和刘铁棍子123子456'
    lst=re.findall("刘.??",strvar)
    print(lst) #['刘', '刘', '刘']

    lst=re.findall("刘.+?",strvar)
    print(lst) #['刘能', '刘老', '刘铁']

    lst=re.findall("刘.*?",strvar)
    print(lst) #['刘', '刘', '刘']

    lst=re.findall("刘.{1,100}?",strvar)
    print(lst) #['刘能', '刘老', '刘铁']
    #贪婪
    lst=re.findall("刘.*子",strvar)
    print(lst) #['刘能和刘老根儿和刘铁棍子123子']
    #非贪婪
    lst=re.findall("刘.*?子",strvar)
    print(lst) #['刘能和刘老根儿和刘铁棍子']

    ####边界符  ^ $
    """
    卡在左边界:w
    卡在右边界:d

    任何的正则表达式,字符左边都加上:r防止转译
    """
    strvar="word pwd sef"
    lst=re.findall(r"w.*",strvar)
    print(lst) #['word pwd sef']
    lst=re.findall(r".*?d",strvar)
    print(lst) #['word', ' pwd']
    lst=re.findall(r"w.*?d",strvar)
    print(lst) #['word']
    #单独匹配word
    lst=re.findall(r"wS*",strvar)
    print(lst) #['word']

    """
    ^ 必须以....开头
    $ 必须以....结尾
    无论是 ^ 还是 $ ,都需要吧字符串看成一个整体
    """
    strvar="大哥大嫂大爷"
    # print(re.findall("大.",strvar)) #['大哥', '大嫂', '大爷']
    # print(re.findall("^大.",strvar)) #['大哥']
    # print(re.findall("大.$",strvar)) #['大爷']
    # print(re.findall("^大.$",strvar)) #[]
    # print(re.findall("^大.*?$",strvar)) #['大哥大嫂大爷']
    # print(re.findall("^大.*?大$",strvar)) #[] 必须以大字开头,以爷字结尾
    print(re.findall("^大.*?爷$",strvar)) #['大哥大嫂大爷']


    # print(re.findall("^g.*? ","giveme lgfive gay")) #['giveme ']
    # print(re.findall("five$","aassfive")) #['five']
    # print(re.findall("^giveme$","giveme")) #['giveme']
    # print(re.findall("^giveme$","giveme giveme")) #[]
    # print(re.findall("giveme","giveme giveme")) #['giveme', 'giveme']
    # print(re.findall("^g.*e","giveme lgfive gay")) #['giveme lgfive']
    3.##分组匹配
    import re
    """
    #1.正常分组()
    1)正常情况下用()圆括号进行分组 可以用1 反向引用第一个圆括号匹配的内容
    2)(?:正则表达式)表示取消优先显示的功能
    """
    print(re.findall('.*?_good','wusir_good alex_good secret男_good')) #['wusir_good', ' alex_good', ' secret男_good']
    print(re.findall('(.*?)_good','wusir_good alex_good secret男_good')) #['wusir', ' alex', ' secret男']
    #?: 取消优先显示括号的功能;
    print(re.findall('(?:.*?)_good','wusir_good alex_good secret男_good')) #['wusir_good', ' alex_good', ' secret男_good']

    #| 或 把长的字符串放到前面优先匹配,把短的容易匹配的放到后面
    strvar="abcabcd"
    lst=re.findall("abc|abcd",strvar)
    print(lst) #['abc', 'abc']
    lst=re.findall("abcd|abc",strvar)
    print(lst) #['abc', 'abcd']

    #匹配小数
    strvar="3.14 56 89.78 78abc"
    lst=re.findall("d+.d+",strvar)
    print(lst) #['3.14', '89.78']

    #匹配小数和整数
    strvar="3.14 56 89.78 78abc"
    lst=re.findall("d+.+d+|d+",strvar)
    print(lst) #['3.14', '56', '89.78', '78']

    #用分组匹配小数和整数
    #(.+d+)表达小数 ()优先匹配显示小括号的内容
    strvar="3.14 56 89.78 78abc"
    lst=re.findall("d+(.+d+)?",strvar)
    print(lst)
    #()不优先匹配显示小括号的内容
    lst=re.findall("d+(?:.+d+)?",strvar)
    print(lst) #['3.14', '56', '89.78', '78']

    #匹配135或171手机号
    lst=re.findall("171[0-9]{8}|135d{8}","17188886666 13566668888 13366668888")
    print(lst) #['17188886666', '13566668888']
    #加 ^ 和 $ 意味着只能写一组手机号,开头和结尾,不能是多个
    lst=re.findall("^171[0-9]{8}$|135d{8}","17188886666")
    print(lst)
    print("-------------")
    #search 函数
    """
    seach 只匹配到一个就返回,返回的是对象
    可以让分组的内容和正常匹配的结果同时显示;

    findall 从左到右把所有的符合条件的内容都返回到列表
    不可以同时显示分组和正常匹配的结果
    """
    obj=re.search("^171[0-9]{8}$|135d{8}","17188886666")
    print(obj)
    #obj.group() 用来获取该对象匹配到的值
    res=obj.group()
    print(res)

    #匹配 www.baidu.com 或者 www.oldboy.com
    strvar="www.baidu.com www.oldboy.com"
    obj=re.search("(www).(baidu|oldboy).(com)",strvar)
    res=obj.group()
    print(res) #www.baidu.com

    #显示分组里面的内容
    res=obj.group(1) #www 显示第一个小括号的内容
    res=obj.group(2) #baidu 显示第二个小括号的内容
    res=obj.group(3) #com 显示第三个小括号的内容
    # res=obj.group(4) #error
    print(res)

    #一次显示所有内容
    res=obj.group()
    print(res)

    #用findall 来做 分组内容和正常匹配的内容二者之间不能同时显示,只能同一时间显示
    lst=re.findall("(www).(baidu|oldboy).(com)",strvar)
    print(lst) #[('www', 'baidu', 'com'), ('www', 'oldboy', 'com')]
    lst=re.findall("(?:www).(?:baidu|oldboy).(?:com)",strvar)
    print(lst) #['www.baidu.com', 'www.oldboy.com']
    print("--------------")
    #5*6-7/3 匹配 5*6 或者 7/3 search
    #d+[*/]d+
    strvar="5*6-9/3 "
    obj=re.search("d+[*/]d+",strvar)
    #返回对象结果
    def calc(strvar):
    if "*" in strvar:
    num1,num2 = strvar.split("*")
    return float(num1)*float(num2)

    if "/" in strvar:
    num1,num2 = strvar.split("/")
    return float(num1)/float(num2)


    res=obj.group()
    print(res) #5*6
    num=str(calc(res))
    print(num) #30.0

    #把5*6得到的结果 替换成 num
    res2=strvar.replace(res,num) #replace只能替换成字符串,所以上面的num要强转为str
    print(res2,type(res2)) #-7/3

    #把剩下的字符串再匹配一边
    obj=re.search("d+[*/]d+",res2)
    print(obj.group()) #7/3
    res3=obj.group()
    num=str(calc(res3))
    print(num) #3.0

    #把最后得到的结果 取代原来的9/3
    res4=res2.replace(res3,num) #replace只能替换成字符串,所以上面的num要强转为str
    print(res4,type(res4)) #30.0-3.0 <class 'str'>

    strvar="<h1>大标题</h1>"
    obj=re.search("<(.*?)>.*?<(.*?)>",strvar)
    print(obj.groups()) #('h1', 'h1')

    ###反向引用 1表达把第一个括号里面的内容再使用一次;
    strvar="<h1>大标题</h1>"
    obj=re.search(r"<(.*?)>.*?</(1)>",strvar)
    print(obj.groups()) #('h1', 'h1')
    4.###反射
    class Man():
    pass

    class Woman():
    pass

    class Children(Man,Woman):
    """
    成员属性:hair skin
    成员方法:cry eat __drink
    功能:描述小孩的属性
    """
    hair="black"
    skin="yellow"
    #绑定方法
    def cry(self):
    print("小孩会哭")

    def eat():
    print("小孩喜欢吃饼干")

    def smile(self,func):
    #__name__ 获取函数名
    res=func.__name__
    print(res)
    def __drink(self):
    print("小孩喜欢喝奶奶")
    obj=Children()
    obj.abc=10
    # __dict__ 获取对象或类的内部成员结构
    print(obj.__dict__) #{}
    #{'__module__': '__main__', 'hair': 'black', 'skin': 'yellow', 'cry': <function Children.cry at 0x1013592f0>, '_Children__drink': <function Children.__drink at 0x1013590d0>, '__doc__': None}
    print(Children.__dict__)

    # __doc__ 获取对象或类的内部文档
    print(obj.__doc__) #成员属性:hair skin 成员方法:cry eat __drink 功能:描述小孩的属性
    print(obj.__doc__) #成员属性:hair skin 成员方法:cry eat __drink 功能:描述小孩的属性

    # __name__ 获取类名或函数名
    def ceshi():
    print(123)
    obj.smile(ceshi)

    # __class__ 获取当前所属类
    print(obj.__class__) #<class '__main__.Children'>

    # __bases__ 获取一个类直接继承的所有父类,返回元组
    res=Children.__bases__
    res2=Children.__base__
    print(res) #(<class '__main__.Man'>, <class '__main__.Woman'>)
    print(res2) #<class '__main__.Man'>

    ###反射
    """
    #概念:通过字符去操作类对象 或者 模块中的属性方法
    """
    # (1)hasattr() 检测对象/类是否有指定成员
    res=hasattr(obj,"hair")
    res=hasattr(obj,"cry")
    print(res)
    res=hasattr(Children,"hair")
    res=hasattr(Children,"eat")
    print(res)

    # (2)getattr() 获取对象/类成员的值
    res=getattr(obj,"hair")
    print(res) #black
    func=getattr(obj,"cry")
    func()
    res=getattr(Children,"skin")
    print(res)
    func1=getattr(Children,"eat")
    func1()
    """
    def cry(self):
    print("小孩会哭")
    如果通过对象反射出来的绑定方法,里面的self这个参数自动传递
    def eat():
    print("小孩喜欢吃饼干")
    如果通过类 反射出来的方法,里面的self这个参数手动传递
    """
    print("-------")
    #通过对象反射的
    func=getattr(obj,"cry")
    func()
    #小孩会哭
    #通过类反射的
    func=getattr(Children,"cry")
    func(123124345454) #让形参实参保持一致,self需要手动传递
    #小孩会哭
    print("---------")
    #综合案例
    # res=input("请输入要调用的方法>>>:")
    # if hasattr(Children,res):
    # func=getattr(Children,res)
    # func(12)

    # (3)setattr() 设置对象/类成员的值
    setattr(obj,"eye","蓝色的眼睛")
    print(obj.eye) #蓝色的眼睛
    setattr(Children,"ceshi111",lambda :print("ceshi111"))
    Children.ceshi111() #ceshi111
    """
    一般在类外创建的都是静态方法,无论是对象还是类都可以调用
    在类外创建绑定方法的过程
    import types
    types.MethodType(函数,obj)
    """

    # (4)delattr() 删除对象/类成员的值
    delattr(obj,"eye")
    # obj.eye() #erro
    # delattr(Children,"ceshi111")
    # Children.ceshi111() #erro

    #关于模块的反射
    # sys.modules 返回一个字典,这个字典都是存放的系统的模块
    import sys
    print(sys.modules)
    """
    {'builtins': <module 'builtins' (built-in)>,
    'sys': <module 'sys' (built-in)>, '_frozen_importlib': <module '_frozen_importlib' (frozen)>,
    '_imp': <module '_imp' (built-in)>, '_warnings': <module '_warnings' (built-in)>, '_thread': <module '_thread' (built-in)>, '_weakref': <module '_weakref' (built-in)>,
    '_frozen_importlib_external': <module '_frozen_importlib_external' (frozen)>, '_io': <module 'io' (built-in)>, 'marshal': <module 'marshal' (built-in)>, 'posix': <module 'posix' (built-in)>, 'zipimport': <module 'zipimport' (built-in)>,
    'encodings': <module 'encodings' from '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/encodings/__init__.py'>, 'codecs': <module 'codecs' from '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/codecs.py'>,
    '_codecs': <module '_codecs' (built-in)>, 'encodings.aliases': <module 'encodings.aliases' from '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/encodings/aliases.py'>,
    'encodings.utf_8': <module 'encodings.utf_8' from '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/encodings/utf_8.py'>, '_signal': <module '_signal' (built-in)>,
    '__main__': <module '__main__' from '/Users/mac/PycharmProjects/wenkday_04/day08/fanse.py'>, 'encodings.latin_1': <module 'encodings.latin_1' from '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/encodings/latin_1.py'>, 'io': <module 'io' from '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/io.py'>, 'abc': <module 'abc' from '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/abc.py'>, '_weakrefset': <module '_weakrefset' from '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/_weakrefset.py'>, 'site': <module 'site' from '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site.py'>, 'os': <module 'os' from '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/os.py'>, 'errno': <module 'errno' (built-in)>, 'stat': <module 'stat' from '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/stat.py'>, '_stat': <module '_stat' (built-in)>, 'posixpath': <module 'posixpath' from '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/posixpath.py'>, 'genericpath': <module 'genericpath' from '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/genericpath.py'>, 'os.path': <module 'posixpath' from '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/posixpath.py'>, '_collections_abc': <module '_collections_abc' from '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/_collections_abc.py'>, '_sitebuiltins': <module '_sitebuiltins' from '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/_sitebuiltins.py'>, 'sysconfig': <module 'sysconfig' from '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/sysconfig.py'>, '_sysconfigdata_m_darwin_darwin': <module '_sysconfigdata_m_darwin_darwin' from '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/_sysconfigdata_m_darwin_darwin.py'>, '_osx_support': <module '_osx_support' from '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/_osx_support.py'>, 're': <module 're' from '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/re.py'>, 'enum': <module 'enum' from '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/enum.py'>, 'types': <module 'types' from '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/types.py'>, 'functools': <module 'functools' from '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/functools.py'>, '_functools': <module '_functools' (built-in)>, 'collections': <module 'collections' from '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/collections/__init__.py'>, 'operator': <module 'operator' from '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/operator.py'>, '_operator': <module '_operator' (built-in)>, 'keyword': <module 'keyword' from '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/keyword.py'>, 'heapq': <module 'heapq' from '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/heapq.py'>, '_heapq': <module '_heapq' from '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/lib-dynload/_heapq.cpython-36m-darwin.so'>, 'itertools': <module 'itertools' (built-in)>, 'reprlib': <module 'reprlib' from '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/reprlib.py'>, '_collections': <module '_collections' (built-in)>, 'weakref': <module 'weakref' from '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/weakref.py'>, 'collections.abc': <module 'collections.abc' from '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/collections/abc.py'>, 'sre_compile': <module 'sre_compile' from '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/sre_compile.py'>, '_sre': <module '_sre' (built-in)>, 'sre_parse': <module 'sre_parse' from '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/sre_parse.py'>, 'sre_constants': <module 'sre_constants' from '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/sre_constants.py'>, '_locale': <module '_locale' (built-in)>, 'copyreg': <module 'copyreg' from '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/copyreg.py'>, '_bootlocale': <module '_bootlocale' from '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/_bootlocale.py'>, 'sitecustomize': <module 'sitecustomize' from '/Applications/PyCharm.app/Contents/helpers/pycharm_matplotlib_backend/sitecustomize.py'>}

    """
    # 通过 __main__ 字典的健,直接获取的是当前的模块对象moudle
    mod=sys.modules["__main__"] #<module '__main__' from '/Users/mac/PycharmProjects/wenkday_04/day08/fanse.py'>

    def func1():
    print("这是func1方法")
    def func2():
    print("这是func2方法")
    def func3():
    print("这是func3方法")
    ##通过用户输入,不停的反射模块当中的方法
    while True:
    res=input("请选择要调用的函数>>>:")
    #判断是否存在当前方法
    if hasattr(mod,res):
    #通过字符串反射方法
    func=getattr(mod,res)
    func()
    else:
    print("没有当前方法!")

    5.###socket  发展流出:(套接字 用来收发数据的工具)
    # a.py =>b.py 2个文件直接的交流通过第三个临时文件缓冲文件来进行沟通
    # a想要发送的内容放到临时c文件中,
    # b从临时c文件中进行提取,
    # 最早没有网络的时候,文件直接的交流方式
    #
    # 有了网络之后:
    # 客户端a 发给 客户端b 发消息可以通过网络
    #
    # c/s
    # c:client 客户端
    # s:server 服务端
    # 常用软件:qq ,飞秋, 王者荣耀 , 英雄联盟 ,网易云音乐 , 有道翻译
    # b/s
    # b:brower 浏览器
    # s:server 服务端
    # 常用软件:小程序 网页游戏 微信小程序 支付宝小程序 微博小程序
    #
    # b/s 和 c/s 程序谁更好
    # b/s 优点: 一对多结构
    # (1)b/s 架构程序,不需要下载软件,节省时间和内存空间
    # (2)b/s 架构程序,所见及所得,不需要安装
    # c/s 结构类型 :多对多结构

    #子网掩码:255.255.255.0
    """
    ip1:192.168.10.12
    11000000.10101000.00001010.00001100
    255.255.255.0
    11111111.11111111.11111111.00000000
    #计算ip1 & 子网掩码
    11000000.10101000.00001010.00001100
    11111111.11111111.11111111.00000000
    计算结果:
    11000000.10101000.00001010.00000000
    网段:192.168.10.0
    """
    """
    ip2:192.168.1.16
    11000000.10101000.00000001.00010000
    255.255.255.0
    11111111.11111111.11111111.00000000
    11000000.10101000.00000001.00010000
    计算结果:
    11000000.10101000.00000001.00000000
    网段:192.168.1.0
    """

    #网段1和网段2值不一样,就不在同一个网段,不能护发消息,若想要互发消息,可以改变子网掩码
    #通过修改子网掩码,改变网段
    """
    ip1:192.168.10.12
    255.255.0.0

    11000000.10101000.00001010.00001100
    11111111.11111111.00000000.00000000
    11000000.10101000.00000000.00000000
    网段1:192.168.0.0

    ip2:192.168.1.16
    255.255.0.0

    11000000.10101000.00000001.00010000
    11111111.11111111.00000000.00000000
    11000000.10101000.00000000.00000000
    网段2:192.168.0.0

    网段1==网段2,两个及其可以互发消息
    """
    #常用端口:
    """
    https://blog.csdn.net/qq_20617725/article/details/51015707
    """

    import socket
    sk=socket.socket

    6.四次挥手:
      第一次a向b发送断开链接的消息,表示a也没有文件给b了
      第二次b向a回应接受断开的请求
      第三次b向a发送断开的请求,表示b也没有文件给a了
      第四次a向b被动回应接受断开的请求
      在第三期发送请求之后,会开启2msl最大报文生存周期
      a会不停的回应第四次的消息给b,确保b服务器接受到消息
      防止a冒然断开,导致b不停的发送第三次的断开请求,造成资源内耗
      如果超过2msl生存周期,b还是没有收到断开的请求,a主动断开
      不在发送第四次断开响应请求;

    7.socket

    (1)服务端
    import socket
    #1.创建一个socket对象,默认按照tcp协议创建
    sk=socket.socket()
    #2.绑定IP和port
    """bind(元组),默认本地IP为:127.0.0.1"""
    sk.bind(("127.0.0.1",9000))
    #3.开启监听
    sk.listen()
    #4.三次握手
    """conn 是三次握手后的链接对象,addr是对方的IP和端口号"""
    conn,addr=sk.accept()
    #<socket.socket fd=4, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0, laddr=('127.0.0.1', 9000), raddr=('127.0.0.1', 53587)>
    print(conn)
    #('127.0.0.1', 53587) 任意给了端口号
    print(addr)
    #5.写收发数据的逻辑
    """
    一发一收是一对,发和收要一一匹配
    recv(字符)
    """
    msg=conn.recv(1024)
    print(msg.decode())
    #发送数据
    conn.send("你是个好人....".encode())
    #6.四次挥手
    conn.close()
    #7.退还端口
    sk.close()

    (2) 客户端
    import socket
    #1.创建对象
    sk=socket.socket()
    #2.直接与服务器主机相连接
    """connect(元组)(IP,port)"""
    sk.connect(("127.0.0.1",9000))
    #3.send用来发送消息,recv用来接收消息
    """send(二进制字节流)"""
    sk.send("我爱你".encode("utf-8"))
    #接收数据
    res=sk.recv(1024)
    print(res.decode())
    #4.关闭链接
    sk.close()

    注意:encode 编码,decode 解码     ===>发消息是编码,收消息收解码

    8.多次发消息
    (1)# ###服务端
    import socket
    sk=socket.socket()
    sk.bind(("127.0.0.1",9000))
    sk.listen()
    #listen accept recv 都是阻塞,如果不满足条件,程序不会往下执行;
    while True:
    conn,addr=sk.accept()

    while True:
    res = conn.recv(1024)
    print(res.decode())
    msg=input("message>>>:")
    conn.send(msg.encode())
    if msg=="q":
    break

    conn.close()
    sk.close()
    (2)# ###客户端
    import socket
    sk=socket.socket()
    sk.connect(("127.0.0.1",9000))
    while True:
    message=input("请输入要发送的消息:")
    sk.send(message.encode())
    res=sk.recv(1024)
    if res==b"q":
    break
    print(res.decode())
    sk.close()
    9.UDP发消息
    (1)###服务端
    """如果udp的服务端,只能先收消息,tcp可以先发也可以先收"""
    import socket
    #1. 创建udp对象type=sock.DGRAM 代表udp协议
    sk=socket.socket(type=socket.SOCK_DGRAM)
    #2. 绑定IP和port(在网络中注册该主机)
    sk.bind(("127.0.0.1",9000))
    #3. udp服务器,第一次启动时,一定是先接收数据,再发送数据
    msg,cli_addr=sk.recvfrom(1024)
    print(msg.decode())
    print(cli_addr)
    #4. 关闭链接
    sk.close()
     
    (2)#  ###客户端
    import socket
    #1. 创建udp对象type=sock.DGRAM 代表udp协议
    sk=socket.socket(type=socket.SOCK_DGRAM)
    #2. sendto (要发送的消息,(IP,port))
    sk.sendto("hello world!".encode(),("127.0.0.1",9000))
    #3. 关闭链接
    sk.close()
    10.UDP多次循环发消息
    (1)服务端
    import socket

    sk = socket.socket(type=socket.SOCK_DGRAM)
    sk.bind(("127.0.0.1", 9527))

    while True:

    s_msg, addr = sk.recvfrom(1024)

    if s_msg == b"q":
    sk.sendto("q".encode("utf-8"),addr)
    else:
    print(s_msg.decode("utf-8"))
    r_msg=input("回复信息如下>>>:")
    sk.sendto(r_msg.encode("utf-8"),addr)
    (2)客户端
    import socket

    sk = socket.socket(type=socket.SOCK_DGRAM)
    while True:
    msg = input("请输入>>>:")
    sk.sendto(msg.encode("utf-8"), ("127.0.0.1", 9527))
    re_msg, addr = sk.recvfrom(1024)

    if re_msg == b"q":
    break
    print(re_msg.decode("utf-8"))
     
  • 相关阅读:
    C#8.0——异步流(AsyncStream)
    递归,循环,尾递归
    C#7.2——编写安全高效的C#代码
    Ocelot中文文档-Route
    Ocelot中文文档-Configuration
    Ocelot中文文档-Not Supported
    Ocelot中文文档-Getting Started
    .NET 单元测试的利剑——模拟框架Moq(简述篇)
    输入五个数字,按从大到小的顺序输出
    函数和方法的区别
  • 原文地址:https://www.cnblogs.com/vivian0119/p/11355316.html
Copyright © 2011-2022 走看看