0

I need to pass a list containing five values from python script to html page.I ran a loop and passed the value one by one to html page.But it is printing only the last value in the browser.My html code is in the format:

<html>
<head></head>
<body>
<p>{{value}}</p>
</body>
</html>

Actually I am calculating probability for each class labels using predict_proba(a) using Decision tree.I took out the index having max probability and using that index I took out the top five class labels.I want to render those top labels to my html page. My python script is following:

Here variable 'a' is the set on input and variable 'event' contains all the distinct class labels.

DTC= DecisionTreeClassifier()
DTC.fit(X_train,y_train)
DTC.predict(pandas.DataFrame([a]))
res=DTC.predict_proba([a])
new=list(chain.from_iterable(res))
index=sorted(range(len(new)), key=lambda i: new[i], reverse=True)[
value=[]
for i in index:
        value.append(event[i])
        return render_template('output.html',value=value)

2 Answers2

1

Hi I think what you need to do is join the list elements to a string.

I am assuming you have a list as follows:

xlist = ["mangoes","grapes","apples","oranges"]

Doing the following will give you a single string containing list elements space separated:

xstr = ' '.join(xlist)
print(xstr)

mangoes grapes apples oranges

If you want them each to be inside separate p tags you can try the following:

xstr = ""
for e in xlist:
    xstr+='<p>'+e+'</p>'
print(xstr)

<p>mangoes</p><p>grapes</p><p>apples</p><p>oranges</p>

And now you can pass the string to the html. Hope this fixes your issue.

 This is the modified code .I need to print the output in browser in tabular format.
    def getLabel(i):

               db = MySQLdb.connect("localhost","root","","cpi" )
               cursor=db.cursor()
               cursor.execute('''select meaning from code where 
               code ='%d' ''' % (i))
               data=cursor.fetchall()
               return data
      xstr1 = ""
      for i in index:
            xstr1 +=str(getLabel(event[i]))+" "


      return render_template('output.html',value=xstr1) 


This is output.html
<html>
<head>
</head>

    <body>
        <table>

            {{value}}
        </table>
    </body>


</html>
  • I have attached my python script as well.Can please check it and suggest. – Bishakha Kumari May 03 '18 at 06:23
  • @BishakhaKumari I believe each time you call the render_template() you render the complete page using the given value. So by calling it in the loop you are rendering the page whole page again and again. You have to move the render_template function call outside the for loop. Also you are passing a list into the be printed inside the p tag, which I don't think is what you are looking for. Please do try out my solution and see if it does what you need. – Chris Aby Antony May 03 '18 at 06:36
  • Thank You,It worked but if I wish to print all the values in tabular format in browser, I am unable to do that.It is printing in one row.Please Suggest something. – Bishakha Kumari May 03 '18 at 07:06
  • @BishakhaKumari You can make them appear in next lines by adding a
    tag. `xstr += '

    ' + e + '


    '`. Or if you want it to be exactly tabular you can replace p tags with tags and enclose the variable inside tags in the html file. Please share how exactly you want it to look and also sample values in the list if you want full code solution.
    – Chris Aby Antony May 03 '18 at 07:24
  • Suppose after appling above solution,values stored in xstr is :xstr= 25 33 40 53 52. There exist some meaningful string for each value which I need to get it from database MySQL and then render that meaning associated with each value to the html page.Let us assume :25-blue whale, 33- Sea water,..so on. i.e. I need to print the meaning of each values fetching from database to the browser through python script in tabular format.I am using flask framework – Bishakha Kumari May 03 '18 at 08:39
0

Modified answer as per discussion in comments:

I'm assuming that these numbers here act like an id and each has a corresponding unique value(meaning). In that case you can modify it as follows:

xstr = ""
for id in xlist:
    xstr+='<tr><td>' + id + ' </td><td>' + getLabel(id) + '</td></tr>'

Now you should define getLabel() such that it takes in the id as argument and fetches the corresponding Label from your database and return it.

Also your html file should be like:

<body>
    <table>
        <tr>
            <th>Id</th>
            <th>Name</th>
        </tr>
        {{value}}<!--This will be a set of table rows -->
    </table>
</body>
  • def getLabel(i): db =MySQLdb.connect("localhost","root","","contextual_intelligence_provider" ) cursor=db.cursor() cursor.execute(''' select meaning from list where code='i' ''') data=cursor.fetchall() return data xstr = "" for id in index: xstr+='' + str(event[id]) + ' ' + getLabel(str(event[id])) + '' print(xstr) return render_template('output.html',value=xstr) still I am getting TypeError: must be str, not tuple – Bishakha Kumari May 07 '18 at 04:40
  • @BishakhaKumari Hi I believe the variable `data` is a tuple(kind of like lists) since it stores the output of an sql query(since it may have more than one rows).Try printing out data[0] and modify return statement accordingly to return the Label. Please do submit formatted code, this is kind of messy. Also this issue is totally out of the scope from your initial question,it is recommended that such questions be posted as a new one. So please mark the answer as a solution if it solved your initial issue. Again let me know in the comments what data[0] prints, if you still need help. – Chris Aby Antony May 07 '18 at 06:07
  • @BishakhaKumari Please refer this : https://stackoverflow.com/questions/12867140/python-mysqldb-get-the-result-of-fetchall-in-a-list?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa – Chris Aby Antony May 07 '18 at 06:17
  • I am getting IndexError: tuple index out of range. Each class label contains only one specified meaning. – Bishakha Kumari May 07 '18 at 06:52
  • ok then try printing data instead of data[0] and let me know what it outputs. – Chris Aby Antony May 07 '18 at 07:21
  • I am getting the Error: tuple index out of range when I give data[0]. Actually when I tried to see type of xstr it gives str type.But the event is of integer type.xstr is containing string. – Bishakha Kumari May 07 '18 at 09:11
  • @BishakhaKumari Okay please try printing simply 'data' without index [0] – Chris Aby Antony May 07 '18 at 09:13
  • if I am trying without index then TypeError: must be str, not tuple is the output. – Bishakha Kumari May 07 '18 at 09:17
  • @BishakhaKumari I hope you tried something like this: `def getLabel(i): db =MySQLdb.connect("localhost","root","","contextual_intelligence_provider" ) cursor=db.cursor() cursor.execute(''' select meaning from list where code='i' ''') data=cursor.fetchall() print("Data is ",data) return "Label"` – Chris Aby Antony May 07 '18 at 09:29
  • I have returned data not label.What is label?I think there is some problem in type casting because my event is of integer type ,its meaning is in string form and the variable xstr in which I am trying to get all top 5 values is of string type.Also when I am trying to pass that value to getlabel(id), there comes an error :must be str not tuple – Bishakha Kumari May 07 '18 at 09:51
  • @BishakhaKumari "Label" is just some arbitrary string given so function executes normally(ie; to avoid getting must be str not tuple). The goal here was to try and see what is being stored in the tuple variable 'data'. Please try it with the above given code. – Chris Aby Antony May 07 '18 at 10:12
  • I am able to get the list along with its meaning but when I am rendering it to browser, it is displaying :(('blue whale',),)(('blue sea',),)(('green grass' ,),).This I need to print in tabular format in browser. – Bishakha Kumari May 07 '18 at 11:38
  • @BishakhaKumari So did you fix the tuple issue and are you able to successfully get labels from database now? – Chris Aby Antony May 07 '18 at 11:42
  • Yes, but not able to display it in browser in tabular format – Bishakha Kumari May 07 '18 at 11:49
  • @BishakhaKumari Ok that's great. Can you edit your question and add your latest python for loop and html code? – Chris Aby Antony May 07 '18 at 11:52