parser-mismatch-id.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #! /usr/bin/python
  2. ## This script checks for mismatched brackets in input parse trees.
  3. ## The following types of mismatches are supported:
  4. ## - total opening/closing bracket number conflict
  5. ## - early exceeding closing brackets
  6. ##
  7. ## This script is built upon no well-known bracketing mishmatch in
  8. ## parsing context.
  9. ##
  10. ## To do: upgarde to support them
  11. ##
  12. ## Version 1.0
  13. import sys, optparse
  14. ##======================================================================
  15. ## main
  16. def main(argv=None):
  17. if argv is None:
  18. argv = sys.argv
  19. parser = optparse.OptionParser(usage="%prog <PARSE FILE>" +
  20. "\nChecks the input parse trees and outputs the line numbers of trees containing mismatched brackets.", version="%prog 1.0")
  21. (opts, posArgs) = parser.parse_args()
  22. if len(posArgs) < 1:
  23. parser.error("At least 1 argument is needed!")
  24. ## opening input parse file
  25. vParseFileName = posArgs[0]
  26. if vParseFileName == None:
  27. print 'Weka pasre file is not provided!'
  28. sys.exit(2)
  29. else:
  30. try:
  31. vParseFile = open(vParseFileName, 'r')
  32. except IOError:
  33. print 'Can\'t open parse file: ' + vParseFileName
  34. sys.exit(2)
  35. vTreeCntr = 1
  36. for vTree in vParseFile:
  37. vBracketCntr = 0
  38. for vChr in vTree:
  39. if vChr == '(':
  40. vBracketCntr += 1
  41. elif vChr == ')':
  42. vBracketCntr -= 1
  43. ## cheking for exceeding number of closing brackets throughout the tree
  44. ## It may happen that at some points in a tree number of closing brackets
  45. ## exceed that of opening brackets but finally the total number of opening
  46. ## and closing brackets in tree be equal (e.g. ())(() which is wrong)
  47. if vBracketCntr < 0:
  48. print vTreeCntr
  49. continue
  50. # final check for the equality of numbers of openning and closing brackets
  51. if vBracketCntr != 0:
  52. print vTreeCntr
  53. vTreeCntr += 1
  54. ##======================================================================
  55. ## calling main
  56. if __name__ == "__main__":
  57. sys.exit(main())