练习:统计一句英文中单词出现的次数,并排序输出到html页面
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
#!/usr/bin/env python
#coding:utf-8
content
=
"who have touched their lives Love begins with a smile grows with a kiss and ends with a tear The brightest future will always be based on a forgotten past you can’t go on well in lifeuntil you let go of your past failures and heartaches"
# 将文本拼接成word:num的字典形式
#循环列表,并且将单词作为字典的key,每出现一次这个单词,key+1
result
=
{}
for
s
in
content.split(
" "
):
if
s
in
result:
result[s]
+
=
1
else
:
result[s]
=
1
#print result
# 字典翻转拼接为num:word的字典
res
=
{}
for
k,v
in
result.items():
res.setdefault(v,[])
res[v].append(k)
#print res
count
=
0
f
=
open
(
'tongji.html'
,
'a+'
)
f.write(
"<html><table style='border:solid 1px'>"
)
f.write(
"<th style='border:solid 1px'>次数</th><th style='border:solid 1px'>单词</th>"
)
while
count <
4
:
key
=
max
(res.keys())
print
"出现了%s次的单词:%s"
%
(key,res[key])
for
word
in
res[key]:
f.write(
'<tr><td style="border:solid 1px">%s</td><td style="border:solid 1px">%s</td></tr>'
%
(key,word))
res.pop(key)
count
=
count
+
1
f.write(
"</table></html>"
)
f.close()
|
本文转自 shouhou2581314 51CTO博客,原文链接:http://blog.51cto.com/thedream/1830128,如需转载请自行联系原作者