Return to Snippet

Revision: 43836
at March 31, 2011 20:04 by Woodoo


Initial Code
# written in Python 3.2

import codecs
import re

inputFilePath = 'testfile.lua'
inputLuaFile = codecs.open( inputFilePath, 'r', encoding = 'utf-8-sig' )
inputLuaFileDataList = inputLuaFile.read().split( "
" )
inputLuaFile.close()

outputFilePath = 'testfile_out.lua'
outputLuaFile = codecs.open( outputFilePath, 'w', encoding = 'utf-8' )
outputLuaFile.write( codecs.BOM_UTF8.decode( "utf-8" ) )

def create_compile( patterns ):
    compStr = '|'.join( '(?P<%s>%s)' % pair for pair in patterns )
    regexp = re.compile( compStr )

    return regexp

comRegexpPatt = [( "oneLineS", r"--[^\[\]]*?$" ),
                 ( "oneLine", r"--(?!(-|\[|\]))[^\[\]]*?$" ),
                 ( "oneLineBlock", r"(?<!-)(--\[\[.*?\]\])" ),
                 ( "blockS", r"(?<!-)--(?=(\[\[)).*?$" ),
                 ( "blockE", r".*?\]\]" ),
                 ( "offBlockS", r"---+\[\[.*?$" ),
                 ( "offBlockE", r".*?--\]\]" ),
                 ]

comRegexp = create_compile( comRegexpPatt )

comBlockState = False

for i in inputLuaFileDataList:
    res = comRegexp.search( i )
    if res:
        typ = res.lastgroup
        if comBlockState:
            if typ == "blockE":
                comBlockState = False
                i = res.re.sub( "", i )
            else:
                i = ""
        else:
            if typ == "blockS":
                comBlockState = True
                i = res.re.sub( "", i )
            else:
                comBlockState = False
                i = res.re.sub( "", i )
    elif comBlockState:
        i = ""

    if not i == "":
        outputLuaFile.write( "{}\n".format( i ) )

outputLuaFile.close()

Initial URL


Initial Description
Hi Guys,

I had a job to remove all kinds of comments from the Lua file. I tried to find a usable Python script to this on the net, but Google did not help.
Therefore, I made one. This script recognizes all types of comments such as single and multi-Line comments. You can find some good comment examples on this site.

I would welcome your opinion.

Initial Title
Python 3.2 Lua comment remover.

Initial Tags
python

Initial Language
Python