青岛澄润国际贸易有限公司

现在的位置: 主页 > 在线留言 > 文章列表

文章正文

python基础教程笔记-项目1-即时标记-Day1

作者:青岛澄润国际贸易有限公司 来源:wwww.usabcc.com 发布时间:2017-09-03 12:42:46
python基础教程笔记-项目1-即时标记-Day1

目标:将文本文件(.txt)转换成网页(.html)

测试文档test_input.txt:

Welcome to World Wide Spam, Inc. These are the corporate web pages of *World Wide Spam*, Inc. We hope you find your stay enjoyable, and that you will sample many of our products. A short history of the company World Wide Spam was started in the summer of 2000. The business concept was to ride the dot-com wave and to make money both through bulk email and by selling canned meat online. After receiving several complaints from customers who weren't satisfied by their bulk email, World Wide Spam altered their profile, and focused 100% on canned goods. Today, they rank as the world's 13,892nd online supplier of SPAM. Destinations From this page you may visit several of our interesting web pages: - What is SPAM? (http://wwspam.fu/whatisspam) - How do they make it? (http://wwspam.fu/howtomakeit) - Why should I eat it? (http://wwspam.fu/whyeatit) How to get in touch with us You can get in touch with us in *many* ways: By phone (555-1234), by email (wwspam@wwspam.fu) or by visiting our customer feedback page (http://wwspam.fu/feedback).书中simple_markup.py执行效果:



首先应把文本切分成块:

收集所有遇到的行,直到遇到一个空行,站群,然后返回已收集的行。这些返回的行就是一个块。之后再次开始收集。不需要收集空行,也不要返回空块。

同时,要确保文件的最后一行是空行,否则程序就不知道最后一个块什么时候结束。vcD4KPHA+zsSxvr/pyfqzycb3dXRpbC5weaO6PC9wPgo8cD48L3A+CjxwcmUgY2xhc3M9"brush:java;">def lines(file): for line in file: yield line yield '\n' def blocks(file): block = [] for line in lines(file): if line.strip(): block.append(line) elif block: yield ''.join(block).strip() block = []lines生成器只是在文件的最后追加一个空行blocks生成器实现了前面说明的方法。

概念:生成器(generator)

什么是生成器?

先看一段JAVA代码:

import java.util.ArrayList; import java.util.List; public class test { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub List list = new ArrayList(); for (int i = 0; i < 10; ++i) list.add("Num:" + i); for (String str : list) System.out.println(str); } } 代码功能为在List中插入字符串"Num0"至"Num9",并打印出来。执行效果:

生成器也是这个效果,现在看这段python代码:

def func(): yield 0 yield 1 yield 2 for i in func(): print i执行结果:



另外网上看到生成器还有next()方法(类似JAVA的迭代器?):

def func(): yield 0 yield 1 yield 2 f = func() print f.next() print f.next() for i in func(): print i 执行结果:



下面利用生成器打印300以下的斐波那契数列:

def get_fib(): a = b = 1 yield a yield b while a + b < 300: a,b = b,a+b yield b for num in get_fib(): print num 执行结果:



暂时感觉生成器就是这么一个东西。

现在再看代码util.py:

1.首先看下生成器lines(file):

def lines(file): for line in file: yield line yield '\n' 测试下: a = [1,2,3,4,5] b = ['hi','how are you','how do you do'] def lines(arg): for line in arg:yield line yield '\n' for i in lines(a): print i for j in lines(b): print j执行结果:


lines生成器的作用为在文件的最后追加一个空行


企业建站2800元起,携手武汉肥猫科技,做一个有见地的颜值派!更多优惠请戳:神农架网站建设 http://shennongjia.45qun.com

COPYRIGHT © 2015 青岛澄润国际贸易有限公司 ALL RIGHTS RESERVED.

网站地图 技术支持:肥猫科技
精彩专题:网站建设
购买本站友情链接、项目合作请联系客服QQ:2500-38-100