初始版本:
-
#!/usr/bin/env python
-
#-*- coding:utf-8 -*-
-
'''
-
python基础教程第2版 20 项目1:即时标记
-
主要使用正则
-
将一段文本转换成有格式的
-
-
'''
-
import sys,re
-
#找出块
-
#收集所有行,直到空行,然后返回已经收集的行.
-
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 = []
-
-
-
print('
测试
')
-
title=True
-
for block in blocks(sys.stdin):
-
block = re.sub(r'\*(.+?)\*',r'\1',block)
-
if title:
-
print('
')
-
print(block)
-
print('')
-
title=False
-
else:
-
print('
')
-
print(block)
-
print('
')
-
print('')
进一步处理:
html.py(主要执行程序)
-
#!/usr/bin/env python
-
#-*- coding:utf-8 -*-
-
'''
-
-
'''
-
import sys,re
-
from util import *
-
from handler import *
-
from rules import *
-
-
class Parser:
-
def __init__(self,handler):
-
self.handler=handler
-
self.rules=[]
-
def addRule(self,rule):
-
self.rules.append(rule)
-
def parse(self,file):
-
self.handler.start('document')
-
for block in blocks(file): #应用规则
-
# print(self.rules)
-
for rule in self.rules:
-
if rule.condition(block):
-
last=rule.action(block,self.handler)
-
if last:
-
break
-
self.handler.end('document')
-
class BasicTextParser(Parser):
-
#处理文本需要渲染器
-
def __init__(self,handler):
-
#调用父类的初始化
-
Parser.__init__(self,handler)
-
#调用父类的方法
-
self.addRule(ListRule()) #添加文章格式规则
-
self.addRule(ListItemRule())
-
self.addRule(TitleRule())
-
self.addRule(HeadingRule())
-
self.addRule(ParagraphRule())
-
-
handler=HTMLRenderer()
-
parser=BasicTextParser(handler)
-
#parser.parse(sys.stdin)
-
parser.parse(sys.stdin)
分割模块:util.py
-
#!/usr/bin/env python
-
#-*- coding:utf-8 -*-
-
'''
-
这个模块主要实现把文本分成区块.
-
'''
-
def lines(file):
-
for line in file: #读取文件,生成每一行的迭代器
-
yield line
-
yield '\n'
-
def blocks(file):
-
block=[]
-
for line in lines(file):#从迭代器中取出每一行
-
if line.strip(): #如果为空,退出;有内容,添加block列表中
-
block.append(line)
-
elif block: #如果上面有空行,再次判断,如果block列表中有内容,生成block列表块;没有内容说明是多行空行,忽略.
-
yield ''.join(block).strip()
-
block=[]
规则模块:rules.py
-
#!/usr/bin/env python
-
#-*- coding:utf-8 -*-
-
'''
-
-
'''
-
from util import *
-
class Rule:
-
"""
-
Base class for all rules.
-
"""
-
def action(self, block, handler):
-
handler.start(self.type)
-
handler.feed(block)
-
handler.end(self.type)
-
return True
-
-
class HeadingRule(Rule):
-
"""
-
A heading is a single line that is at most 70 characters and
-
that doesn't end with a colon.
-
"""
-
type = 'heading'
-
def condition(self, block):
-
return not '\n' in block and len(block) <= 70 and not block[-1] == ':'
-
-
class TitleRule(HeadingRule):
-
"""
-
The title is the first block in the document, provided that it is
-
a heading.
-
"""
-
type = 'title'
-
first = True
-
-
def condition(self, block):
-
if not self.first: return False
-
self.first = False
-
return HeadingRule.condition(self, block)
-
-
class ListItemRule(Rule):
-
"""
-
A list item is a paragraph that begins with a hyphen. As part of
-
the formatting, the hyphen is removed.
-
"""
-
type = 'listitem'
-
def condition(self, block):
-
return block[0] == '-'
-
def action(self, block, handler):
-
handler.start(self.type)
-
handler.feed(block[1:].strip())
-
handler.end(self.type)
-
return True
-
-
class ListRule(ListItemRule):
-
"""
-
A list begins between a block that is not a list item and a
-
subsequent list item. It ends after the last consecutive list
-
item.
-
"""
-
type = 'list'
-
inside = False
-
def condition(self, block):
-
return True
-
def action(self, block, handler):
-
if not self.inside and ListItemRule.condition(self, block):
-
handler.start(self.type)
-
self.inside = True
-
elif self.inside and not ListItemRule.condition(self, block):
-
handler.end(self.type)
-
self.inside = False
-
return False
-
-
class ParagraphRule(Rule):
-
"""
-
A paragraph is simply a block that isn't covered by any of the
-
other rules.
-
"""
-
type = 'paragraph'
-
def condition(self, block):
-
return True
渲染模块:handler.py
-
#!/usr/bin/env python
-
#-*- coding:utf-8 -*-
-
'''
-
-
'''
-
class Handler():
-
def callback(self,prefix,name,*args):
-
mothed=getattr(self,prefix+name,None)
-
if callable(mothed): #加一层判断,如果对象是可调用的才返回
-
return mothed(*args)
-
def start(self,name):
-
self.callback('start_',name)
-
def end(self,name):
-
self.callback('end_',name)
-
-
class HTMLRenderer(Handler):
-
'''
-
用于生成HTML的具体处理程序
-
HTMLRender内的方法都可以通过超类处理程序的start(),end(),sub()方法来访问,它们实现了用于HTML文档的基本标签.
-
-
'''
-
-
def start_document(self):
-
print('
html
')
-
def end_document(self):
-
print('')
-
-
def start_paragraph(self):
-
print('
')
-
def end_paragraph(self):
-
print('
')
-
-
def start_heading(self):
-
print('
')
-
def end_heading(self):
-
print('')
-
-
def start_list(self):
-
print('
')
-
def end_list(self):
-
print('
')
-
-
def start_listitem(self):
-
print('
-
')
-
def end_listitem(self):
-
print('
')
-
-
def start_title(self):
-
print('
')
-
def end_title(self):
-
print('')
-
-
def feed(self,data):
-
print(data)
-
-
'''
-
getattr(object, name[, default])
-
Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example, getattr(x, 'foobar') is equivalent to x.foobar. If the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised.
-
callable(object)
-
Return True if the object argument appears callable, False if not. If this returns true, it is still possible that a call fails, but if it is false, calling object will never succeed. Note that classes are callable (calling a class returns a new instance); class instances are callable if they have a __call__() method.
-
'''
-
-
#下面是给XML渲染
test_input.txt
-
Required Entitlements and Repositories
-
-
The packages provided in the following repositories are required to install and configure a functioning Red Hat Enterprise Virtualization environment. When one of these repositories is required to install a package, the steps required to enable the repository are provided in the appropriate location in the Installation Guide or *Self-Hosted Engine Guide*.
-
-
Red Hat Enterprise Virtualization Manager
-
-
Red Hat Enterprise Virtualization Hypervisor 6 hosts are supported in Red Hat Enterprise Virtualization 3.6 only in clusters with 3.5 compatibility. Clusters with 3.6 compatibility support Red Hat Enterprise Virtualization Hypervisor 7 hosts and Red Hat Enterprise Linux 7 hosts only.
-
-
The following Red Hat Enterprise Virtualization features are not supported:
-
- Hot-plug CPU
-
- SPICE display
-
- SmartCard
-
- Sound device
-
- Watchdog
-
-
ntegration with OpenStack Networking (Neutron), *OpenStack* Image (Glance), and OpenStack Volume (Cinder)
执行测试:
-
[t@bjb0541 untitled]$ ./B20util.py < test_input.txt |tee > 2.html
-
<html><head><title>测试</title><body>
-
<h1>
-
Required Entitlements and Repositories
-
</h1>
-
<p>
-
The packages provided in the following repositories are required to install and configure a functioning Red Hat Enterprise Virtualization environment. When one of these repositories is required to install a package, the steps required to enable the repository are provided in the appropriate location in the Installation Guide or <em>Self-Hosted Engine Guide</em>.
-
</p>
-
<p>
-
Red Hat Enterprise Virtualization Manager
-
</p>
-
<p>
-
Red Hat Enterprise Virtualization Hypervisor 6 hosts are supported in Red Hat Enterprise Virtualization 3.6 only in clusters with 3.5 compatibility. Clusters with 3.6 compatibility support Red Hat Enterprise Virtualization Hypervisor 7 hosts and Red Hat Enterprise Linux 7 hosts only.
-
</p>
-
<p>
-
The following Red Hat Enterprise Virtualization features are not supported:
-
- Hot-plug CPU
-
- SPICE display
-
- SmartCard
-
- Sound device
-
- Watchdog
-
</p>
-
<p>
-
ntegration with OpenStack Networking (Neutron), <em>OpenStack</em> Image (Glance), and OpenStack Volume (Cinder)
-
</p>
-
</body></html>
进一步版本执行测试:
[t@bjb0541 makeuphtml]$ python html.py < test_input.txt > 1.html
阅读(1226) | 评论(0) | 转发(0) |