版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/cadi2011/article/details/86373184
# -*- coding:utf-8 -*-
#面试题,写一个方法,将一行字符串中所有单词出现的数量统计出来
words = "hello hello what time tian hao hao tian hao hao love love love you love you"
def wordCount(source):
if isinstance(source, str):
word_list = source.split() #解bug,用默认的split()方法,能满足需求
print word_list
word_dict = {}
for ele in word_list:
if ele in word_dict:
word_dict[ele] = word_dict[ele] + 1
else:
word_dict[ele] = 1
print word_dict
else:
print "not a str"
wordCount(words)