用状态机STATE MACHINE实现有选择的文件转换

用书上的例子实现在解析HTML文本时,对"<>"中的符号不进行字符转换。

用状态机STATE MACHINE实现有选择的文件转换
import sys
import string
from optparse import OptionParser

CHAR_MAP = dict(zip(
    string.ascii_lowercase,
    string.ascii_lowercase[13:26] + string.ascii_lowercase[0:13]
    )
)

class RotateStream(object):
    """
    General purpost ROT13 Translator
    A ROT13 translator smart enough to skip
    Markup tags if that's what we want.
    """
    MARKUP_START = '<'
    MARKUP_END = '>'
    def __init__(self, skip_tags):
        self.skip_tags = skip_tags
    def rotate13_letter(self, letter):
        """
        Return the 13-char rotation of a letter.
        """
        do_upper = False
        if letter.isupper():
            do_upper = True
        letter = letter.lower()
        if letter not in CHAR_MAP:
            return  letter
        else:
            letter = CHAR_MAP[letter]
            if do_upper:
                letter = letter.upper()

        return letter
    def rotate_from_file(self,handle):
        """
        Rotate from a file handle.
        Take a file-like object and translates
        text file it into ROT13
        """
        state_markup = False
        for 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 = char
                    else:
                        #Not in a markup state, rotate
                        #unless we're starting a new tag
                        if char == self.MARKUP_START:
                            state_markup = True
                        else:
                            char = self.rotate13_letter(char)
                else:
                    char = self.rotate13_letter(char)
                #Make this a generator
                yield char

if __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)
用状态机STATE MACHINE实现有选择的文件转换

用状态机STATE MACHINE实现有选择的文件转换

用状态机STATE MACHINE实现有选择的文件转换

上一篇:Linux驱动技术(七) _内核定时器与延迟工作


下一篇:WCF技术剖析之十:调用WCF服务的客户端应该如何进行异常处理