python统计字符串中单词数量

统计字符串中单词数量
题目内容:
读入一个字符串,内容为英文文章,输入其中出现最多的单词(仅输入单词,不计算标点符号,同一个单词的大小写形式合并计数),统一以小写输出。

输入格式:
this is a python and Python

输出格式:
python

使用比较基本的方法写的参考代码:

#!/usr/bin/env python
#  -*- coding: utf-8 -*-
#python 2.7
import re
print u'请输入字符串:'
wz = raw_input()
s = wz.lower()
#小写单词的正则表达式
r='[a-z]+'
#找到所有单词
ws = re.findall(r,s)
#定义一个字典来存储单词和次数
dt = {}
for w in ws:
dt[w] = dt.setdefault(w,0)+1
#wd来存储单词集合,可能有几个,比如2个单词,都出现30次
wd = []
#max用来存储单词出现的最多的次数
max = 0
for word,times in dt.items():
if times>max:
wd = []
wd.append(word)
max = times
elif times == max:
wd.append(word)

print u'有%s个单词,出现频率最高:'%len(wd)
for x in wd:
print "%s\t%s"%(x,max)

测试

请输入字符串:
A good beginning makes a good ending!!!
有2个单词,出现频率最高:
a       2
good    2

温馨提示:答案为网友推荐,仅供参考