1

这是我在没有 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

​​​

4

4 回答 4

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>
于 2013-05-13T10:26:17.193 回答
1

Pythoncollections模块包含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))
于 2013-05-13T10:20:13.293 回答
1

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

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

应该

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

而且您的return声明在 final 之前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

于 2013-05-13T10:16:45.203 回答
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>

希望这对你有帮助!

于 2013-05-13T10:06:31.930 回答