两篇文章掌握Python语法和内置函数功能(第二篇)
2017-09-04 17:02
423 查看
Overview
这篇文章是接着上篇文章写的,主要介绍Python的字典结构,操作文件,正则表达式。上篇文章链接如下:http://blog.csdn.net/xlinsist/article/details/50866079
字典
先看看下面的例子:## 构建一个字典 dict = {} ## 向字典中存入键值对 dict['a'] = 'alpha' dict['g'] = 'gamma' dict['o'] = 'omega' ## {'a': 'alpha', 'o': 'omega', 'g': 'gamma'} print dict ## Simple lookup, returns 'alpha' print dict['a'] ## Put new key/value into dict dict['a'] = 6 'a' in dict ## True ## print dict['z'] ## Throws KeyError if 'z' in dict: print dict['z'] ## Avoid KeyError print dict.get('z') ## None (instead of KeyError) ## 如果没有这个Key值,将返回xlinsist print dict.get('z', 'xlinsist')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,任何类型都可以作为一个值。
接下来,介绍几种遍历字典的方法:
## 这个key是以随机的顺序遍历的 for key in dict: print key ## 与上面方法相同,都是遍历key for key in dict.keys(): print key ## 返回一个包含所有key的列表 dict.keys() ## 返回一个包含所有value的列表 dict.values() ## .items() is the dict expressed as (key, value) tuples print dict.items() ## [('a', 'alpha'), ('o', 'omega'), ('g', 'gamma')] for k, v in dict.items(): print k, '-->', v ## a --> xlnb ## o --> omega ## g --> gamma1
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
格式化字典:
hash = {} hash['count'] = 42 hash['word'] = 'garfield' # %d 代表 int, %s 代表 string s = 'I want %(count)d copies of %(word)s' % hash # 'I want 42 copies of garfield'1
2
3
4
5
6
7
1
2
3
4
5
6
7
del操作符:
# 移除定义的变量 var a = 5 del a # 移除列表中的元素 list = ['a', 'b', 'c', 'd'] del list[0] ## Delete first element del list[-2:] ## Delete last two elements print list ## ['b'] # 移除字典中的元素 dict = {'a':1, 'b':2, 'c':3} del dict['b'] ## Delete 'b' entry print dict ## {'a':1, 'c':3}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()函数能打开文件并返回一个文件指针。# 'r'读、'w'写、'a'追加 f = open('foo.txt', 'rU') for line in f: print line # 把整个文件读取到内存中并返回以文件的行作为元素的列表 f.readlines() # 读取整个文件作为一个字符串 f.read() # 向文件中写入字符串 f.write(string) f.close()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次
来个例子:
## i+ = one or more i's, as many as possible. match = re.search(r'pi+', 'piiig') => found, match.group() == "piii" ## Finds the first/leftmost solution, and within it drives the + ## as far as possible (aka 'leftmost and largest'). ## In this example, note that it does not get to the second set of i's. match = re.search(r'i+', 'piigiiii') => found, match.group() == "ii" ## \s* = zero or more whitespace chars ## Here look for 3 digits, possibly separated by whitespace. match = re.search(r'\d\s*\d\s*\d', 'xx1 2 3xx') => found, match.group() == "1 2 3" match = re.search(r'\d\s*\d\s*\d', 'xx12 3xx') => found, match.group() == "12 3" match = re.search(r'\d\s*\d\s*\d', 'xx123xx') => found, match.group() == "123" ## ^ = matches the start of string, so this fails: match = re.search(r'^b\w+', 'foobar') => not found, match == None ## but without the ^ it succeeds: match = re.search(r'b\w+', 'foobar') => found, match.group() == "bar"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。在看下面的例子:
str = r'\n' match = re.search(r'\n', str) if match: print 'found', match.group() ## 'found word:cat' else: print 'did not find'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’.
## 方括号中的点就是字面上的意义,并没有什么特殊的含义 match = re.search(r'[\w.-]+@[\w.-]+', 'purple alice-b@google.com monkey dishwasher') if match: print match.group() ## 'alice-b@google.com'1
2
3
4
1
2
3
4
[^ab] 匹配除了 ‘a’ or ‘b’的任何字符。
用括号做组抽取
str = 'purple alice-b@google.com monkey dishwasher' match = re.search('([\w.-]+)@([\w.-]+)', str) if match: print match.group() ## 'alice-b@google.com' (the whole match) print match.group(1) ## 'alice-b' (the username, group 1) print match.group(2) ## 'google.com' (the host, group 2)1
2
3
4
5
6
1
2
3
4
5
6
findall()函数找到字符串中的所有匹配项,并以字符串列表的形式返回。
## Suppose we have a text with many email addresses str = 'purple alice@google.com, blah monkey bob@abc.com blah dishwasher' ## Here re.findall() returns a list of all the found email strings emails = re.findall(r'[\w\.-]+@[\w\.-]+', str) ## ['alice@google.com', 'bob@abc.com'] for email in emails: # do something with each found email string print email1
2
3
4
5
6
7
8
1
2
3
4
5
6
7
8
str = 'purple alice@google.com, blah monkey bob@abc.com blah dishwasher' tuples = re.findall(r'([\w\.-]+)@([\w\.-]+)', str) print tuples ## [('alice', 'google.com'), ('bob', 'abc.com')] for tuple in tuples: print tuple[0] ## username print tuple[1] ## host1
2
3
4
5
6
1
2
3
4
5
6
以上内容整理自Google’s Python Class
https://developers.google.com/edu/python/dict-files
相关文章推荐
- 两篇文章掌握Python语法和内置函数功能(第二篇)
- 两篇文章掌握Python语法和内置函数功能(第一篇)
- 两篇文章掌握Python语法和内置函数功能(第一篇)
- 查看python 3中的内置函数列表,以及函数功能描述
- ipython, 一个 python 的交互式 shell,比默认的python shell 好用得多,支持变量自动补全,自动缩进,支持 bash shell 命令,内置了许多很有用的功能和函数
- Python成长之路第二篇(1)_数据类型内置函数用法
- Python成长之路第二篇(1)_数据类型内置函数用法
- 这篇文章主要介绍了Python使用函数默认值实现函数静态变量的方法,是很实用的功能
- python模块与包的了解,__name__的功能,包中函数的导入
- 写一个函数,识别字符串是否符合python语法的变量名
- Python的内置功能讲解
- Python 利用内置set函数对字符串和列表进行去重的方法
- 机器人概率定位学习笔记第二篇_使用python建立机器人感知函数(sense fuction)
- Python内置的字符串处理函数整理
- 以上的文章是我解决这样一个问题时候的大致的思路: 把Matlab读取二进制文件的函数变成VBA读取二进制文件,实现同样的功能
- python中的内置函数总结
- Python常见内置高效率函数用法示例
- Python 利用内置set函数对字符串和列表进行去重
- 通过jpype来用python来调用sikuli功能函数
- Python 语法知识 --函数,闭包