Python 3.2 Lua comment remover.


/ Published in: Python
Save to your folder(s)

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.


Copy this code and paste it in your HTML
  1. # written in Python 3.2
  2.  
  3. import codecs
  4. import re
  5.  
  6. inputFilePath = 'testfile.lua'
  7. inputLuaFile = codecs.open( inputFilePath, 'r', encoding = 'utf-8-sig' )
  8. inputLuaFileDataList = inputLuaFile.read().split( "
  9. " )
  10. inputLuaFile.close()
  11.  
  12. outputFilePath = 'testfile_out.lua'
  13. outputLuaFile = codecs.open( outputFilePath, 'w', encoding = 'utf-8' )
  14. outputLuaFile.write( codecs.BOM_UTF8.decode( "utf-8" ) )
  15.  
  16. def create_compile( patterns ):
  17. compStr = '|'.join( '(?P<%s>%s)' % pair for pair in patterns )
  18. regexp = re.compile( compStr )
  19.  
  20. return regexp
  21.  
  22. comRegexpPatt = [( "oneLineS", r"--[^\[\]]*?$" ),
  23. ( "oneLine", r"--(?!(-|\[|\]))[^\[\]]*?$" ),
  24. ( "oneLineBlock", r"(?<!-)(--\[\[.*?\]\])" ),
  25. ( "blockS", r"(?<!-)--(?=(\[\[)).*?$" ),
  26. ( "blockE", r".*?\]\]" ),
  27. ( "offBlockS", r"---+\[\[.*?$" ),
  28. ( "offBlockE", r".*?--\]\]" ),
  29. ]
  30.  
  31. comRegexp = create_compile( comRegexpPatt )
  32.  
  33. comBlockState = False
  34.  
  35. for i in inputLuaFileDataList:
  36. res = comRegexp.search( i )
  37. if res:
  38. typ = res.lastgroup
  39. if comBlockState:
  40. if typ == "blockE":
  41. comBlockState = False
  42. i = res.re.sub( "", i )
  43. else:
  44. i = ""
  45. else:
  46. if typ == "blockS":
  47. comBlockState = True
  48. i = res.re.sub( "", i )
  49. else:
  50. comBlockState = False
  51. i = res.re.sub( "", i )
  52. elif comBlockState:
  53. i = ""
  54.  
  55. if not i == "":
  56. outputLuaFile.write( "{}\n".format( i ) )
  57.  
  58. outputLuaFile.close()

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.