#!/usr/bin/pythonimport sysclass Article: """Converts text files to HTML, for use in web pages. The output will not be a full HTML page, just the relevant HTML. The file: "Hello World. Paragraph 1. Paragraph 2. Another line." Would be converted to: "<h1>Hello World</h1> <p>Paragraph 1.</p> <p>Paragraph 2.<br/> Another line.</p>" All CSS should be done by the user, this would probably be made easy by encapsulating the article in a <div id='article> block.'""" def __init__(self, inFile): """Reads text from the files and then passes it through to the __parse() function""" try: textFile = open(inFile, 'r') self.text = textFile.read() textFile.close() except IOError: print "File failed to open or be read from, aborting." sys.exit(1) self.parse(self.text) def parse(self, text): """Splits text into paragraphs, calls __parseParagraph on each one, then joins them""" self.textParagraphs = self.text.strip().split('\n\n') self.htmlParagraphs = [] for i in range(0, len(self.textParagraphs)): print "Parsing paragraph " + str(i+1) self.htmlParagraphs.append(self.__parseParagraph(self.textParagraphs[i])) self.html = "\n".join(self.htmlParagraphs) def __parseParagraph(self, paragraph): """Converts paragraph to HTML.""" paragraph = '<p>' + paragraph.replace('\n', '<br/>\n') paragraph = self.__tagReplace(paragraph) + '</p>' return paragraph def __tagReplace(self, paragraph): """Converts BBCode to HTML""" tagStack, retParagraph = [], "" while 1: start = paragraph.find('[') if (start == -1): break retParagraph += paragraph[0:start] paragraph = paragraph.replace(paragraph[0:start], '') end = paragraph.find(']') tag = paragraph[1:end] if tag[0] == '\\': if tag[1:] != tagStack[-1]: print "Unmatched " + '[' + tagStack.pop() + ']' + " tag, aborting." print "Paragraphs contained: " + paragraph sys.exit(1) else: tagStack.pop() else: tagStack.append(tag) retParagraph += '<' + tag + '>' paragraph = paragraph.replace(paragraph[:end+1], '') retParagraph += paragraph while len(tagStack): tag = tagStack.pop() retParagraph += '<\\' + tag + '>' return retParagraphif __name__ == "__main__": Test = Article('hello.txt') print Test.html