今天心血来潮,重学了一下python。去年学了一段时间的python,各种原因就搁置下来了,如今发现爬虫这项技能还是蛮重要的,以后找数据,找资料,数据可视化,网络安全都用得到。
本文笔记来源:https://www.bilibili.com/video/BV1ws411i7Dr?p=26
简单的例子 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 import re m = re.findall("abc" ,"xxxxxxxxxxx" ) 目标串和原始串 print m\\单个数字 m = re.findall("\d" , "xxxxxxxxxxxxxxx" ) \\连续的4 个数字 m = re.findall("\d\d\d\d" , "xxxxxxxxxxxxxxx" ) .匹配任意字符 *无限 .*无限匹配任意字符 r原始无转义 \\贪婪匹配 m = re.findall(r"<div>(.*)<\div>" , "<div>xxx<\div><div>xxx<\div>" ) \\非贪婪 m = re.findall(r"<div>(.*?)<\div>" , "<div>xxx<\div><div>xxx<\div>" )
1 2 贪婪匹配————['xxx<\div><div>xxx' ] 非贪婪———— ['xxx' ,'xxx' ]
语法 匹配除了换行符之外的 1 2 3 4 >>> import re>>> m = re.findall("." ,"aa\nabbcc" )>>> print m['a' , 'a' , 'a' , 'b' , 'b' , 'c' , 'c' ]
匹配转义 1 2 m = re.findall("\." ,"aa.abbcc" )
匹配字符集 1 2 m = re.findall("a[bcd]ef" ,"aaabdfgcc" )
数字 1 m = re.findall("\d" , "12p3b456" )
非数字 1 m = re.findall("\D" , "12p3b456" )
空白字符\非空白字符 1 2 3 4 5 m = re.findall("\s" , "12 p\tab456" ) m = re.findall("\S" , "12 p\tab456" )
只匹配字母数字\只配特殊字符 1 2 3 4 m = re.findall("\w" , "12 +#p\tab456" ) m = re.findall("\W" , "12 +#p\tab456" )
匹配开头/结尾 1 2 m = re.findall("^abc" ,"abcabc" ) m = re.findall("abc$" ,"abcabc" )
参考http://www.yuqiaochuang.com/:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 不区分大小写 m = re.findall("abc" , "abcdABc" , re.I) print m 匹配换行 s = "<div>hello\nworld</div>" m = re.findall(r"<div>(.*)</div>" , s, re.S) print m 匹配多行 m = re.findall("^abc" , "abc\nabc" ) print m m = re.findall("^abc" , "abc\nabc" , re.M) print m m = re.findall(r"<div>(.*)<\div>" , "<div>xx\nx<\div><DIV>xxx<\div>" , re.I)
平时看document!!! 看document看document看document,重要的事情说3遍