Python正则表达式
正则表达式是个魔鬼,也是个天使。在你没有掌握它之前,它是魔鬼,在你掌握它后,它是天使,但是,时
不时还是要跳出来,给你调皮捣蛋一番。
一个正则表达式就是由普通字符以及特殊字符组成的文字模式,该模式描述在查找文字主体时待
匹配的一个或多个字符串。正则表达式作为一个模板,将某个字符模式与所搜索的字符串进行匹配,并能提取出匹配的结果。它是搜索、替换和解析复杂字符模式的
一种强大而标准的方法。
正则表达式有着总体规范的一套语法,但是到了各种语言中,又会有使用上的稍微不同,主要是表达式的细
微语法表达,还有语言的匹配类和方法的不同。
Python的所有类库都在re包中,和java
1.4以后的不同,String的各个方法,find和replace都不自做主张的去使用正则表达式,而是使用简单的字符串方式。这点我比较欣赏,有时
候只是做一些简单的替换,不要弄正则表达式这么麻烦,也让新手们摸不着北,替换两个字符就要去了解正则表达式这么夸张。
工具
Python有一个非常好的正则表达式辅助调试工具:Kodos。有Windows版本,提供了对正则表达式的方便的实时调试功能,建议学习正则表达式前
一定要下载:
http://kodos.sourceforge.net/
应用场景:
转换url为路径名
import
re
articleUrl =
"http://pp.sohu.com/yule/photoview-44789795.html#44789795"
path =
re.sub("http://|https://", "", articleUrl)
path =
re.sub("[?&.=#-]", "_", path)
path
'pp_sohu_com/yule/photoview_44789795_html_44789795'
采用这种替换方式,随时发现url中有新非法字符,添加到[]中就可以了。[]表示字符集,在[]其中的任意字符,都会被匹配到
2. 提取html页面中img标签的src属性
import
re
import
urllib
imgSrcPattern
=
r
'''
<img\s*src\s*="?(\S+)"?
'''
pageUrl
=
'
http://pp.sohu.com/yule/photoview-44789
相关文档:
队列:
与堆栈类似,通过python的列表类型来实现,参考 help(list)
shoplist=['apple','mango','carrot','banana']
print 'I have',len(shoplist),'items to purchase'
print 'these items are:'
for item in shoplist:
print item,
shoplist.append('rice')
print 'my shopping list is now', shoplist
shoplist. ......
#from pp3e Chapter 9.3
#############################################################################
# popup three new window, with style
# destroy() kills one window, quit() kills all windows and app; top-level
# windows have title, icon, iconify/deiconify and protocol for wm events;
# there ......
list.append(item)
list.extend(sequence)
http://docs.python.org/tutorial/datastructures.html
http://docs.python.org/library/functions.html 这几天看一下
python howto
恩。python documentation 确实很好很强大啊!
list.append(x)Add an item to the end of the list; equivalent to a[len(a):]&n ......
用Python提取文件夹下的特定扩展名的文件
不知道什么时候,网闲着没用,挂了个linux的视屏教程,里面有很多个文件夹,有很多无关的文件。这对于像我没收藏垃圾文件癖好的人来说,简直是 ......
refer from: http://www.daniweb.com/forums/thread115282.html#
python
Syntax
(Toggle Plain Text
)
# respond to a key
without the need to press
enter
import
Tkinter
as tk
def
keypress(
event)
:
if
event.keysym
== 'Escape'
:
root.destroy
......