2013年10月27日

Python Cookbook学习记录 ch2_6/7/8_2013/10/27

摘要: 2.6 处理文件中的每一词a.先获取每一行,再通过split()方法获取每一个词,之后再进行处理for line in open(thefilepath): for word in line.split(): dosomethingwith(word)b.使用生成器(generator),将元素的迭代,和元素的处理分开def words_of_file(thefilepath, line_to_words=str.split): the_file = open(thefilepath): for line in the_file: for word... 阅读全文

posted @ 2013-10-27 21:22 七海之风 阅读(129) 评论(0) 推荐(0)

Python Cookbook学习记录 ch2_4/5_2013/10/27

摘要: 2.4从文件中读取指定的行从根据给定的行号,从文本中读取一行数据使用python 标准库中linecache模块>>> import linecache>>> theline = linecache.getline('thefile.txt',3)>>> print thelineUsing this simple program as a basis, computer science principles or elements of a specific programming language can be expl 阅读全文

posted @ 2013-10-27 20:10 七海之风 阅读(142) 评论(0) 推荐(0)

Python Cookbook学习记录 ch2_3_2013/10/27

摘要: 2.3搜索和替换文件中的文本需要将文件中的某个字符串改变成另外一个。字符串中replace方法提供了字符串替换最简单的办法:>>> s = 'hello world'>>> s.replace('l','L')'heLLo worLd'搜索替换需要两个文件,先第一个文件,再通过replace方法将里面的内容进行铁环,再讲替换完的内容输入到另外一个文件中>>> file_object = open('thefile.txt')>>> file_t 阅读全文

posted @ 2013-10-27 17:42 七海之风 阅读(131) 评论(0) 推荐(0)

Python Cookbook学习记录 ch2_2_2013/10/27

摘要: 2.2写入文件a.将一个长字符串写入文件:open('thefile.txt', 'w').write(all_the_text) # text to a text fileopen('abinfile', 'wb').write(all_the_data) # data to a binary fileb.先付给一个对象,处理完毕后在关闭文件file_object = open('thefile.txt', 'w')file_object.write(all_the_text)file_objec 阅读全文

posted @ 2013-10-27 17:24 七海之风 阅读(119) 评论(0) 推荐(0)

Python Cookbook学习记录 ch2_1_2013/10/27

摘要: 开始第二章的学习,第二章讲的是python对文件的操作2.1读取文件既然是文件操作,那么就必须先有文件,在如下目录“E:\PythonCookbook\CHA2”创建文件后,在交互模式下发现python无法直接读取文件,文件木有找到>>> all_the_text = open('thefile.txt').read()Traceback (most recent call last): File "", line 1, in all_the_text = open('thefile.txt').read()IOError: 阅读全文

posted @ 2013-10-27 16:52 七海之风 阅读(170) 评论(0) 推荐(0)

Python Cookbook学习记录 ch1_19_2013/10/27

摘要: 1.19检查字符串中的结束标记系统有内建函数startswith()和endswith()来检查字符串的开始和结束字符1 >>> s='hello'2 >>> s.endswith('o')3 True4 >>> s.startswith('h')5 True本节使用方法检查字符串S中是否包含多个结束标记中的一个。文中推荐了一种快捷优雅的方法:>>> import itertools>>> def anyTrue(predicate,sequence): r 阅读全文

posted @ 2013-10-27 15:35 七海之风 阅读(152) 评论(0) 推荐(0)

导航