Html Generator

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • JediKnight83
    New Member
    • Jul 2008
    • 3

    Html Generator

    I want to generate a script that produces html code. I have tried out must parts of the code from the shell .Somehow I always get errors if I check the modul.
    please help me find the syntax errors...
    Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on win32
    Type "copyright" , "credits" or "license()" for more information.

    *************** *************** *************** *************** ****
    Personal firewall software may warn about the connection IDLE
    makes to its subprocess using this computer's internal loopback
    interface. This connection is not visible on any external
    interface and no data is sent to or received from the Internet.
    *************** *************** *************** *************** ****

    IDLE 1.2
    >>>



    ##generates html table code from CSV Files
    ##it must be copied to right section in html file for now
    ----------------------------------------------------------
    ---------------------------------------------------------------------
    ##this is an example of the table
    ##...
    ##<td align=\"right\" class=\"tableHi ghlightVertical \">smile</td>
    ##</tr>
    ##_____________ _______________ _______________ _______________ _
    ##_____________ _______________ _______________ _______________
    ##this is an exaple row of the csv
    ##1;Patrick Pleifer;16;6;13 ;0;20;0;55;0;55
    ##_____________ _______________ _______________ _______________ __
    ##_____________ _______________ _______________ _______________ ____
    ##
    ## First part read out csv, fill array
    ##_____________ _______________ _____________
    ## starting coding..definit ion of variables
    import logging

    ##logging.basic Config(level=lo gging.DEBUG, doesn't work somehow
    ## format='%(ascti me)s %(levelname)s %(message)s',
    ## filename='/temp/myapp.log',
    ## filemode='w')

    demitterCSV = ';'
    CSVFile= 'meinfile.csv'
    Outputfile ='outputfile.ht ml'

    logging.debug(' csv demitter = ' + demitterCSV)
    logging.debug(' csv file = ' + CSVFile)
    logging.debug(' csv file = ' + Outputfile)

    # used css styles in col order
    ColStyleList = ['tableHighlight Vertical','tabl eStandardCenter MinWname','tabl eStandardCenter MinW','tableSta ndardCenterMinW ','tableStandar dCenterMinW','t ableStandardCen terMinW','table StandardCenterM inW','tableStan dardCenterMinW' ,
    'tableStandardC enterMinW','tab leStandardCente rMinW','tableHi ghlightVertical ']
    logging.debug(' css array generated = ' + ColStyleList)


    numCol = len(ColStyleLis t)

    import csv


    #read data into a 2d array
    array = []
    #reader = csv.reader(open (CSVFile, "rb"), demitterCSV) doesn't work with variables(why?? )
    reader = csv.reader(open ("meinfile.csv" , "rb"), delimiter=";")
    logging.debug(' csv afile opened = ')
    for row in reader:
    array.append(ro w)

    reader.close()
    numRows= len(array)
    if numRows ==len(array[1]:
    logging.debugwa rning("csv format does not match table col format")
    else:
    logging.debug(' auslesen fertig ,array erzeugt; Anzahl Reihen = '+ numRows ' Spalten = '+ numCol)

    #______________ _______________ __________
    #______________ _______________ _______________ _
    # First part is over :read out is complete
    #Second part: generating html code
    #______________ _______________ ______________-
    # temporarly html code is safed in array
    #

    mycode =[]
    mycode.append(" ""<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">""")
    mycode.append(' <html>')
    mycode.append(' <head>')
    mycode.append(" ""<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">""")
    mycode.append(" ""<title>TI TLE</title>""")
    mycode.append(" ""<link href="pokerDeta il.css" rel="stylesheet " type="text/css" />""")
    mycode.append(" ""<style type="text/css">""")

    rowdefstart = u'<tr height=\\\"19\\ \">'
    rowdefend= r"</tr>"
    colldefstart = '<td class=\\'
    collstyladd= '"\>'
    colldefend = r"</td>"

    logging.debug(" Header in temp array")
    logging.debug(m ycode)
    numRows= len(array)

    #<td class=\"tableHi ghlightVertical \">smile</td>


    row=0
    col=0
    tmp= "tmp"
    while row < numRows:
    logging.debug(( "counter " + str(row)+" < " + str(numRows))
    #mycode.append( rowdefstart)
    while col <numCol:
    logging.debug(" outer " + str(row)+ " counter " + str(col)+" < "+ str(numCol))
    tmp=(colldefsta rt + ColStyleList[col] + collstyladd+str (array[row][col])+ colldefend)
    mycode.append(s )
    col = col + 1
    col = 0
    row = row + 1
    logging.debug()


    # tmp string is needed, if you put sequence escape string direcly in array
    # it screws it, see below
    #<td class=\\tableHi ghlightVertical "\\>1.</td>' instead of
    #<td class=\"tableHi ghlightVertical \">smile</td>

    writer = csv.writer(open ("some.csv", "wb"))
    writer.writerow s(mycode)
    logging.debug(" finished")


    Thanks for your help. I am really curious as I normally cope with java.
    At least I was able to solve some (previous) errors like escape sequence myself...but now I am kind of stuck
  • kaarthikeyapreyan
    New Member
    • Apr 2007
    • 106

    #2
    Hey could u please put the code in the
    Code:
    <code block>
    so that the indents could be visible

    Comment

    • JediKnight83
      New Member
      • Jul 2008
      • 3

      #3
      Sorry
      was offline some time here a new version
      please help me find the syntax errors...
      <code
      class HtmlGenerator:
      ##generates html table code from CSV Files
      #it must be copied to right section in html file for now


      def __init__(self, csvname = 'input.csv'):
      self.CSVFile = csvname
      self.Outputfile = "outputname "
      self.demitterCS V = "demitter"
      self.numRows =0
      self.numCol=0
      self.array = []
      self.ColStyleLi st =
      iteration =['tableHighlight Vertical','tabl eStandardCenter MinWname','tabl eStandardCenter MinW','tableSta ndardCenterMinW ','tableStandar dCenterMinW','t ableStandardCen terMinW','table StandardCenterM inW','tableStan dardCenterMinW' ,
      'tableStandardC enterMinW','tab leStandardCente rMinW','tableHi ghlightVertical ']

      #constants
      TABLE_TAG_END= "<//TABLE>"
      TABLE_TAG_OPEN= "<TABLE "
      ROW_TAG_START = u'<tr height=\\\"19\\ \">'
      ROW_TAG_END= r"</tr>"
      CELL_TAG_OPEN = "<td "
      CLASS_ASSIGN_TA G= " class=\\"
      CLOSE_TAG= '"\>'
      CELL_TAG_CLOSE = r"</td>"



      ##
      ## def __init__(self, csvname = 'input.csv' , outputname ='output.html', demitter =";", colstyle = []):
      ## import logging
      ## import csv
      ## self.CSVFile = csvname
      ## self.Outputfile = outputname
      ## self.demitterCS V = demitter
      ## self.numRows =0
      ## self.numCol=0
      ## self.array = []
      ## self.ColStyleLi st = colstyle
      ## #constants
      ## TABLE_TAG_END= "<//TABLE>"
      ## TABLE_TAG_OPEN= "<TABLE "
      ## ROW_TAG_START = u'<tr height=\\\"19\\ \">'
      ## ROW_TAG_END= r"</tr>"
      ## CELL_TAG_OPEN = "<td "
      ## CLASS_ASSIGN_TA G= " class=\\"
      ## CLOSE_TAG= '"\>'
      ## CELL_TAG_CLOSE = r"</td>"

      #______________ _______________ _______________ _______________ ____________


      # block of set variable methods
      setColumStyles( iteration):
      ColStyleList =iteration

      setCsvFilename( name):
      CSVFile =name

      setOutputFilena me(name):
      Outputfile =name

      setDemitter(dem ):
      demitterCSV=nam e

      self. = outputname

      #______________ _______________ _______________ _______________ _______________ ____

      # block of get mothods

      getColumStyles( ):
      return ColStyleList

      getCsvFilename( ):
      return CSVFile

      getOutputFilena me():
      return Outputfile

      getDemitter():
      return demitterCSV

      #______________ _______________ _______________ _______________ _______________ ____
      # printing and logging methods for iterations
      printIteration( iteration):
      for item in iteration:
      print(str(item) )
      return true


      logIteration(it eration):
      for item in iteration:
      lgging.debug(st r(item))
      return true

      #______________ _______________ _______________ _______________ ___________
      # use this method to replace consol logging with filelogging
      setFileLogging( logname = "errorlog.log") :
      logging.basicCo nfig(level=logg ing.DEBUG,
      format='%(ascti me)s %(levelname)s %(message)s',
      filename="/" + logname,
      filemode='w')
      logging.debug(" Filelog activ "+ "/" + logname)
      return true
      # logs and prints contentr of important variables
      printSettings() :
      print('csv demitter = ' + demitterCSV)
      print('csv file = ' + CSVFile)
      print'csv file = ' + Outputfile)
      print('csv file = ' + (str)ColStyleLi st)
      logging.info('c sv demitter = ' + demitterCSV)
      logging.info('c sv file = ' + CSVFile)
      logging.info('c sv file = ' + Outputfile)
      logging.info('c sv cssSTylelist = /t' + (str)ColStyleLi st )


      #reads in csv data, if relevant variables were not init properly use parameters
      getArryCSV(name =CSVFile, dem=demitterCSV ):
      reader = csv.reader(open ("name", "rb"), delimiter=dem)
      logging.info('c sv afile opened = ')
      array = array []
      for row in reader:
      array.append(ro w)
      numRows= len(array)
      numCol = len(array[0])
      logging.info('c sv read out complete ' )
      logging.info('A nzahl Reihen = '+ numRows ' Spalten = '+ numCol)
      reader.close()
      return true


      isDimOk():
      len(ColStyleLis t)
      if numCol ==len(ColStyleL ist)
      logger.info("di m css style list does not match css file")
      logger.info("cs s disabled");
      return false
      else :
      logging.info("c sv format matches table col format")
      return true


      # produces html header code, which will stored in array, actually html lines are appended! returns true if succesfull
      produceHtmlHmlH eader(iteration ):
      iteration.appen d("""<!DOCTYP E HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">""")
      iteration.appen d('<html>')
      iteration.appen d('<head>')
      iteration.appen d("""<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">""")
      iteration.appen d("""<title>TIT LE</title>""")
      iteration.appen d("""<link href="pokerDeta il.css" rel="stylesheet " type="text/css" />""")
      iteration.appen d("""<style type="text/css">""")
      iteration.debug ("Header in temp array")
      return true





      # appends produced table code to array, return true if no exceptions
      produceHtmlTabl eCode(iteration ):
      # example table cell<td class=\"tableHi ghlightVertical \">smile</td>
      iteration.appen d("<BODY>")
      if (!isDimOk())
      ColStyleList = []
      i=0
      while i <numCol:
      ColStyleList.ap pend(" ")
      i= i+1
      row=0
      col=0
      tmp= "tmp"
      iteration.appen d(TABLE_TAG_OPE N)
      while row < numRows:
      tmp= ROW_TAG_START
      logging.debug(( "counter " + str(row)+" < " + str(numRows))
      iteration.appen d(tmp)
      while col <numCol:
      logging.debug(" outer " + str(row)+ " counter " + str(col)+" < "+ str(numCol))
      tmp=(CELL_TAG_O PEN + CLASS_ASSIGN_TA G + ColStyleList[col] + CLOSE_TAG+str(a rray[row][col])+ CELL_TAG_CLOSE)
      iteration.appen d(tmp)
      col = col + 1
      col = 0
      tmp = ROW_TAG_END
      iteration.appen d(tmp)
      row = row + 1
      tmp = TABLE_TAG_CLOSE
      iteration.appen d(tmp)
      iteration.appen d("<\BODY>")
      # warning no explicit typecasting tmp string is needed, otherwise see below
      #<td class=\\tableHi ghlightVertical "\\>1.</td>'
      #<td class=\"tableHi ghlightVertical \">smile</td>
      return true

      writeCodetoFile (name=output.ht ml,iteration):
      writer = csv.writer(open ("some.csv", "wb"))
      writer.writerow s(iteration)
      logging.info("w rote file :" + name )
      logiteration (iteration)


      test:
      #def _ _init_ _(self, csvname = 'input.csv' , outputname ='output.html', demitter =";", colstyle = []):

      iteration =['tableHighlight Vertical','tabl eStandardCenter MinWname','tabl eStandardCenter MinW','tableSta ndardCenterMinW ','tableStandar dCenterMinW','t ableStandardCen terMinW','table StandardCenterM inW','tableStan dardCenterMinW' ,
      'tableStandardC enterMinW','tab leStandardCente rMinW','tableHi ghlightVertical ']

      checklist []
      AnotherInstance = HtmlGenerator.H tmlGenerator("m einfile.csv","m einhtml.html"," ;",iteration )

      checklist []
      checklist.appen d(AnotherInstan ce.setFileLoggi ng())
      checklist.appen d(AnotherInstan ce.setFileLoggi ng())
      mycode []
      checklist.appen d(AnotherInstan ce.getArryCSV() )
      checklist.appen d(AnotherInstan ce.produceHtmlH mlHeader(mycode ))
      checklist.appen d(AnotherInstan ce.produceHtmlT ableCode(mycode ))
      checklist.appen d(AnotherInstan ce.writeCodetoF ile(mycode))

      block>


      [B]Thanks for your help. I am really curious as I normally cope with java.
      At least I was able to solve some (previous) errors like escape sequence myself...but now I am kind of stuck

      Comment

      • JediKnight83
        New Member
        • Jul 2008
        • 3

        #4
        Code:
        class HtmlGenerator:
            ##generates html table code from CSV Files
            #it must be copied to right section in html file for now
        
              #
              #def __init__(self, csvname = "input.csv"):
              #      self.CSVFile = "csvname"
              #      self.Outputfile = "outputname"
              #      self.demitterCSV = "demitter"
              #      self.numRows =0
              #      self.numCol=0
              #      self.array = []
              #      self.ColStyleList = ['tableHighlightVertical','tableStandardCenterMinWname','tableStandardCenterMinW','tableStandardCenterMinW','tableStandardCenterMinW','tableStandardCenterMinW','tableStandardCenterMinW','tableStandardCenterMinW',
              #  'tableStandardCenterMinW','tableStandardCenterMinW','tableHighlightVertical']
              #
              #      #constants
              #      TABLE_TAG_END= "<//TABLE>"
              #      TABLE_TAG_OPEN=  "<TABLE "
              #      ROW_TAG_START = u'<tr height=\\\"19\\\">'
              #      ROW_TAG_END= r"</tr>"
              #      CELL_TAG_OPEN = "<td "
              #      CLASS_ASSIGN_TAG= " class=\\"
              #      CLOSE_TAG= '"\>'
              #      CELL_TAG_CLOSE = r"</td>"
        
            
            
         
            def __init__(self, csvname = 'input.csv' , outputname ='output.html', demitter =";", colstyle = []):
                    import logging
                    import csv 
                    self.CSVFile = csvname
                    self.Outputfile = outputname
                    self.demitterCSV = demitter
                    self.numRows =0
                    self.numCol=0
                    self.array = []
                    self.ColStyleList = colstyle
                    #constants
                    TAG_TABLE_C= "<//TABLE>"
                    TAG_TABLE_O=  "<TABLE "
                    TAG_ROW_O = u'<tr height=\\\"19\\\">'
                    TAG_ROW_C= r"</tr>"
                    TAG_CELL_O = "<td "
                    TAG_CLASS_O= " class=\\"
                    TAG_CLASS_C= '"\>'
                    TAG_CELL_C = r"</td>"
                    TAG_BODY_O = "<BODY>"
                    TAG_BODY_C = "<\BODY>"
                    TAG_HTML_O = '<html>'
                    TAG_HTML_C = r"</html>"
                    TAG_HEAD_O = '<head>'
                    TAG_HEAD_C = r"</head>"
                    TAG_META_O = "<meta "
                    TAG_META_C = " />"
                    TAG_TITLE_O = "<title>"
                    TAG_TITLE_C = r"</title>"
                    TAG_STYLE_O = "<style "
                    TAG_STYLE_C = r"</style>"
                    tmp= "tmp" 
                #_______________________________________________________________________
        
                 
                # block of set variable methods
            def setColumStyles(iteration):
                    self.ColStyleList =iteration
        
            def setCsvFilename(name):
                    CSVFile =name
                    
            def setOutputFilename(name):
                    Outputfile =name
        
            def setDemitter(dem):
                    demitterCSV=name
        
            
                
                #______________________________________________________________________________
                    
                # block of get mothods
        
            def getColumStyles():
                    return ColStyleList
        
            def getCsvFilename():
                    return str(CSVFile)
                
            def getOutputFilename():
                    return str(Outputfile)
                
            def getDemitter():
                    return str(demitterCSV)
        
            def getTAG_TABLE_O():
                    return str(TAG_TABLE_O)
        
            def getTAG_TABLE_C():
                    return str(TAG_TABLE_C)
        
            def getTAG_ROW_O():
                    return str(TAG_ROW_O)
        
            def getTAG_ROW_C():
                    return str(TAG_ROW_C)
        
            def getTAG_CELL_O():
                    return str(TAG_CELL_O)
        
            def getTAG_CELL_C():
                    return str(TAG_CELL_C)
           
            def getTAG_CLASS_O():
                    return str(TAG_CLASS_O)
        
            def getTAG_CLASS_C():
                    return str(TAG_CLASS_C)
                    
            def getTAG_BODY_O():
                    return str(TAG_BODY_O)
                    
            def getTAG_BODY_C():
                    return str(TAG_BODY_C)
                    
            def getTAG_HTML_C():
                    return str(TAG_HTML_C)
                    
            def getTAG_HTML_O():
                    return str(TAG_HTML_O)
                    
            def getTAG_HEAD_C():
                    return str(TAG_HEAD_C)
                    
            def getTAG_HEAD_O():
                    return str(TAG_HEAD_O)    
                    
            def getTAG_META_C():
                    return str(TAG_META_C)
                    
            def getTAG_META_O():
                    return str(TAG_META_O)             
                    
            def getTAG_TITLE_C():
                    return str(TAG_TITLE_O)
                    
            def getTAG_TITLE_O():
                    return str(TAG_TITLE_C)
                    
            def getTAG_STYLE_C():
                    return str(TAG_STYLE_O)
                    
            def getTAG_STYLE_O():
                    return str(TAG_STYLE_O) 
                   
                  
        
             #______________________________________________________________________________
            # printing and logging methods for iterations
            def printIteration(iteration):
                 for item in iteration:
                    print(str(item))
                 return true
        
                                  
            def logIteration(iteration):
                 for item in iteration:
                    lgging.debug(str(item))
                 return true
        
            #______________________________________________________________________
            # use this method to replace consol logging with filelogging
            def setFileLogging(logname = "errorlog.log"):
                logging.basicConfig(level=logging.DEBUG,                      
                           format='%(asctime)s %(levelname)s %(message)s',
                           filename="/" + logname,
                           filemode='w')
                logging.debug("Filelog activ "+ "/" + logname)
                return true
            # logs and prints contentr of important variables
            def printSettings():
                print('csv demitter = ' + str(getDemitter()))
                print('csv file = ' + str(getCsvFilename()))
                print('outputfile = ' + str(getOutputFilename()))
                print('csv Col Names = ' + str(getColumStyles))                       
                logging.info('csv demitter = ' + str(getDemitter()))
                logging.info('csv file = ' + str(getCsvFilename()))
                logging.info('outputfile = ' + str(getOutputFilename()))
                logging.info('csv Col Names = ' + str(getColumStyles))                       
        
        
            #reads in csv data, if relevant variables were not init properly use parameters
            def getArryCSV(name=CSVFile, dem=demitterCSV):
                reader = csv.reader(open("name", "rb"), delimiter=dem)
                logging.info('csv afile opened = ')
                array = []
                for row in reader:
                    array.append(row)
                numRows= len(array)
                numCol = len(array[0])
                logging.info('csv read out complete ' )
                logging.info("Anzahl Reihen = "+ str(numRows) + " Spalten = " + str(numCol))
                reader.close()
                return true
                
           
            def isDimOk():
              len(ColStyleList)
              if (numCol ==len(ColStyleList)):
                    logger.info("dim css style list does not match css file")
                    logger.info("css disabled");
                    return false
              else :
                    logging.info("csv format matches table col format")
                    return true
        
        
            # produces html header code, which will stored in array, actually html lines are appended! returns true if succesfull
            def produceHtmlHmlHeader(self,iteration):
                iteration.append("""<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">""")
                iteration.append(self.)
                iteration.append('<head>')
                iteration.append("""<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">""")
                iteration.append("""<title>TITLE</title>""")
                iteration.append("""<link href="pokerDetail.css" rel="stylesheet" type="text/css" />""")
                iteration.append("""<style type="text/css">""")
                iteration.debug("Header in temp array")
                return true
            
        
         
        
             
             # appends produced table code to array, return true if no exceptions
            def produceHtmlTableCode(self,iteration):
                 # example table cell<td class=\"tableHighlightVertical\">smile</td> 
                iteration.append("<BODY>")
                ok = isDimOk()
                if(ok == true):
                    ColStyleList = []
                    i=0
                    while i <numCol:
                        ColStyleList.append(" ")
                        i= i+1
                row=0
                col=0
                
                iteration.append(self.getTAG_TABLE_O)
                while row < numRows:
                    logging.debug("counter " + str(row)+" < " + str(numRows))
                    iteration.append(self.getTAG_ROW_O)
                    while col <numCol:
                        logging.debug("outer " + str(row)+ " counter " + str(col)+" < "+ str(numCol))  
                        tmp=(self.getTAG_CELL_O + self.getTAG_CLASS_C + ColStyleList[col] + self.getTAG_CLASS_C+str(array[row][col])+ self.getTAG_CELL_C)
                        iteration.append(tmp)
                        col = col + 1
                    col = 0
                    tmp = self.getTAG_ROW_C
                    iteration.append(tmp)                     
                    row = row + 1
                tmp = str(TABLE_TAG_CLOSE)
                iteration.append(tmp)
                iteration.append("<\BODY>")
                # warning no explicit typecasting tmp string is needed, otherwise see below
                #<td class=\\tableHighlightVertical"\\>1.</td>'
                #<td class=\"tableHighlightVertical\">smile</td>
                return  true   
        
            def writeCodetoFile(self,iteration,name = "output.html" ):
                writer = csv.writer(open("some.csv", "wb"))
                writer.writerows(iteration)
                logging.info("wrote file :" + name )
                logiteration (iteration)
              
        class Test:
        
            def test():
                    #def _ _init_ _(self, csvname = 'input.csv' , outputname ='output.html', demitter =";", colstyle = []):
        
                iteration =['tableHighlightVertical','tableStandardCenterMinWname','tableStandardCenterMinW','tableStandardCenterMinW','tableStandardCenterMinW','tableStandardCenterMinW','tableStandardCenterMinW','tableStandardCenterMinW',
                'tableStandardCenterMinW','tableStandardCenterMinW','tableHighlightVertical']
        
                checklist = []
                AnotherInstance = HtmlGenerator.HtmlGenerator("meinfile.csv","meinhtml.html",";",iteration)
        
                checklist.append(AnotherInstance.setFileLogging())
                checklist.append(AnotherInstance.setFileLogging())
                mycode = []
                checklist.append(AnotherInstance.getArryCSV())                       
                checklist.append(AnotherInstance.produceHtmlHmlHeader(mycode))                       
                checklist.append(AnotherInstance.produceHtmlTableCode(mycode))                     
                checklist.append(AnotherInstance.writeCodetoFile(mycode))

        Comment

        • kaarthikeyapreyan
          New Member
          • Apr 2007
          • 106

          #5
          Hey I got a couple of errors on my dry run

          1. def getArryCSV(name =CSVFile, dem=demitterCSV )
          either define the values of CSVFile and demitterCSV somewhere
          or if they are the values themselves then
          u can do it this way
          Code:
          def getArryCSV(name="CSVFile", dem="demitterCSV")
          2. complete this "iteration.appe nd(self.)" in the "produceHtmlHml Header(self,ite ration)" method

          Comment

          Working...