用书上的例子实现在解析HTML文本时,对"<>"中的符号不进行字符转换。
import sys import string from optparse import OptionParserCHAR_MAP = dict(zip(string.ascii_lowercase,string.ascii_lowercase[13:26] + string.ascii_lowercase[0:13]) )class RotateStream(object):"""General purpost ROT13 TranslatorA ROT13 translator smart enough to skipMarkup tags if that's what we want."""MARKUP_START = '<'MARKUP_END = '>'def __init__(self, skip_tags):self.skip_tags = skip_tagsdef rotate13_letter(self, letter):"""Return the 13-char rotation of a letter."""do_upper = Falseif letter.isupper():do_upper = Trueletter = letter.lower()if letter not in CHAR_MAP:return letterelse:letter = CHAR_MAP[letter]if do_upper:letter = letter.upper()return letterdef rotate_from_file(self,handle):"""Rotate from a file handle.Take a file-like object and translatestext file it into ROT13"""state_markup = Falsefor line in handle:for char in line:if self.skip_tags:if state_markup:#here we're looking for a closing '>'if char == self.MARKUP_END:state_markup = False#char = charelse:#Not in a markup state, rotate#unless we're starting a new tagif char == self.MARKUP_START:state_markup = Trueelse:char = self.rotate13_letter(char)else:char = self.rotate13_letter(char)#Make this a generatoryield charif __name__ == '__main__':parser = OptionParser()parser.add_option('-t', '--tags', dest = "tags",help = "Ignore Markup Tags", default = False,action = "store_true")options, args = parser.parse_args()print("options tags is ", options.tags)rot = RotateStream(options.tags)for letter in rot.rotate_from_file(sys.stdin):sys.stdout.write(letter)