两篇文章掌握Python语法和内置函数功能(第二篇)
2016-03-25 19:51
856 查看
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')
由于字符串和元组都是不可变的,它们可以做为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 --> gamma
格式化字典:
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'
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}
文件
open()函数能打开文件并返回一个文件指针。# 'r'读、'w'写、'a'追加 f = open('foo.txt', 'rU') for line in f: print line # 把整个文件读取到内存中并返回以文件的行作为元素的列表 f.readlines() # 读取整个文件作为一个字符串 f.read() # 向文件中写入字符串 f.write(string) f.close()
如果不确定某文本文件会用什么样的换行符,可以将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"
模式串前的字母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'
上面代码的输出结果为’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'
[^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)
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 email
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] ## host
以上内容整理自Google’s Python Class
https://developers.google.com/edu/python/dict-files
相关文章推荐
- Python动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- Python将excel导入到mysql中
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定
- FREEBASIC 编译可被python调用的dll函数示例
- Python 七步捉虫法