Overview
这篇文章是接着上篇文章写的,主要介绍Python的字典结构,操作文件,正则表达式。上篇文章链接如下:
http://blog.csdn.net/xlinsist/article/details/50866079
字典
先看看下面的例子:
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
由于字符串和元组都是不可变的,它们可以做为key,数字也可以作为key,任何类型都可以作为一个值。
接下来,介绍几种遍历字典的方法:
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
格式化字典:
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 1
- 2
- 3
- 4
- 5
- 6
- 7
del操作符:
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
文件
open()函数能打开文件并返回一个文件指针。
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
如果不确定某文本文件会用什么样的换行符,可以将open的第二个参数设定为 ‘rU’,指定通用换行符转化。这让你可以自由地在Windows、UNIX(包括Mac OS X),以及其他的老Macintosh平台上交换文件,完全不用担心任何问题:无论你的代码在什么平台上运行,各种换行符都被映射成 ‘\n’。
正则表达式
基本的模式
- . (点) – 匹配任何单个字符除了换行符 ‘\n’
- \w – 匹配数字和字母。\W取反
- \s – 匹配空白字符(空格、换行、制表符…)。\S取反
- \t, \n, \r – tab, newline, return
- \d – 匹配数字
- + – 出现1次或更多次
- * – 出现0次或更多次
- ? – 出现0次或1次
来个例子:
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
模式串前的字母r指定python字符串为原始串。先看下面的例子:
由上图可以看出,加r的字符串就是2个字符:’\’和’n’;没加r的字符串python解释器认为它就是一个换行符,所以长度为1。在看下面的例子:
- 1
- 2
- 3
- 4
- 5
- 6
- 1
- 2
- 3
- 4
- 5
- 6
上面代码的输出结果为’did not find’,这是因为str为包含’\’和’n’的两个字符,而正则系统将’\’和’n’相邻认做是换行符,所以并不匹配。但是如果我把上面的str=r’\n’改为str = ‘\n’,那么输出结果为found,\n(这个我们并不一定看见这个字符串,我们会看到控制台上出现一行空白)。
其实我们可以认为正则和python是两个不同的编程语言,对待字符串的方式不相同。更加具体的解释参考:http://stackoverflow.com/questions/12871066/what-exactly-is-a-raw-string-regex-and-how-can-you-use-it
方括号
[abc] 匹配 ‘a’ or ‘b’ or ‘c’.
- 1
- 2
- 3
- 4
- 1
- 2
- 3
- 4
[^ab] 匹配除了 ‘a’ or ‘b’的任何字符。
用括号做组抽取
- 1
- 2
- 3
- 4
- 5
- 6
- 1
- 2
- 3
- 4
- 5
- 6
findall()函数找到字符串中的所有匹配项,并以字符串列表的形式返回。
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 1
- 2
- 3
- 4
- 5
- 6
- 1
- 2
- 3
- 4
- 5
- 6
以上内容整理自Google’s Python Class