2013-05-13 67 views
1

这是我做的时候没有HTML代码如何将列表更改为HTML表格? (蟒蛇)

from collections import defaultdict 

hello = ["hello","hi","hello","hello"] 
def test(string): 
    bye = defaultdict(int) 
    for i in hello: 
     bye[i]+=1 
    return bye 

,我想这个更改为HTML表,这是我迄今为止尝试,但它仍然无法正常工作

def test2(string): 
    bye= defaultdict(int) 
    print"<table>" 
    for i in hello: 
     print "<tr>" 
     print "<td>"+bye[i]= bye[i] +1+"</td>" 
     print "</tr>" 
    print"</table>" 
    return bye 

+2

它仍然不起作用。 >追溯(最近呼叫最后): print“​​“+ bye [i] = bye [i] +1+”“ ^ SyntaxError:无效的语法 – 2013-05-13 10:09:57

+3

这里您的预期输出是什么? – 2013-05-13 10:10:00

+1

@AshwiniChaudhary我需要与第一个相同的输出,但增加了HTML代码 – 2013-05-13 10:11:48

回答

1

您可以使用collections.Counter计算在列表中出现,然后利用这些信息来创建HTML表。 试试这个:

from collections import Counter, defaultdict 

hello = ["hello","hi","hello","hello"] 
counter= Counter(hello) 
bye = defaultdict(int) 
print"<table>" 
for word in counter.keys(): 
    print "<tr>" 
    print "<td>" + str(word) + ":" + str(counter[word]) + "</td>" 
    print "</tr>" 
    bye[word] = counter[word] 
print"</table>" 

这段代码的输出将是(你可以,如果你想更改格式):

>>> <table> 
>>> <tr> 
>>> <td>hi:1</td> 
>>> </tr> 
>>> <tr> 
>>> <td>hello:3</td> 
>>> </tr> 
>>> </table> 

希望这有助于你!

1

您不能在打印语句的中间分配变量。您也不能在打印语句中连接字符串类型和整数类型。

print "<td>"+bye[i]= bye[i] +1+"</td>" 

应该

bye[i] = bye[i] + 1 
print "<td>" 
print bye[i] 
print '</td>' 

而且你return语句在最后print之前,所以它永远不会打印。

全功能

def test2(string): 
    bye= defaultdict(int) 
    print"<table>" 
    for i in hello: 
     print "<tr>" 
     bye[i] = bye[i] + 1 
     print "<td>" 
     print bye[i] 
     print '</td>' 
     print "</tr>" 
     print"</table>" 
     return bye 

这将是你的代码的精确,翻译工作,但我不知道为什么你会以这种方式来。 bye是毫无意义的在这里,因为你只是打印1次每次

1

的Python collections模块包含Counter功能,即做完全,需要什么:

>>> from collections import Counter 
>>> hello = ["hello", "hi", "hello", "hello"] 
>>> print Counter(hello) 
Counter({'hello': 3, 'hi': 1}) 

现在,你想生成的HTML。更好的方法是为此使用现有的库。例如Jinja2。你只需要安装它,例如使用pip:现在

pip install Jinja2 

,代码为:

from jinja2 import Template 
from collections import Counter 

hello = ["hello", "hi", "hello", "hello"] 

template = Template(""" 
<table> 
    {% for item, count in bye.items() %} 
     <tr><td>{{item}}</td><td>{{count}}</td></tr> 
    {% endfor %} 
</table> 
""") 

print template.render(bye=Counter(hello)) 
2
from collections import defaultdict 

hello = ["hello","hi","hello","hello"] 

def test2(strList): 
    d = defaultdict(int) 
    for k in strList: 
    d[k] += 1 
    print('<table>') 
    for i in d.items(): 
    print('<tr><td>{0[0]}</td><td>{0[1]}</td></tr>'.format(i)) 
    print('</table>') 

test2(hello) 

输出

<table> 
    <tr><td>hi</td><td>1</td></tr> 
    <tr><td>hello</td><td>3</td></tr> 
</table>