’’***'统计每个单词出现的个数(三种方法》*
第一种如下:(最简单的方式**)**
‘’’**
sentance = 'I can because i think i can '
#切片分隔成列表序列,用列表推导式表达
rresult = {word: sentance.split ().count ( word ) for word in set ( sentance.split () )}
print ( rresult )
print ( (sentance.split ()) )
统计每个单词出现的个数(第二种)–字典方法(也是比较常见的一种方式)
def word_amount(sentance):
split_str = sentance.split ()
dict_new = {}.fromkeys ( split_str, 0 )
for word_name in split_str:
if word_name not in dict_new.keys ():
dict_new[word_name] = 1
print ( '1' )
else:
dict_new[word_name] += 1
return dict_new
if __name__ == "__main__":
sentance = ' i think i can and can do well'
print ( word_amount ( sentance ) )
第三种方法:****(引用模块,学会使用一些常见的模块)
from collections import Counter
str0 = 'I can because i think i can'
counts = Counter ( str0.split () )
print ( counts )
还有第四种方法,就是__len__ 和__getitem__,
(置字典方法和魔术方法的结合)较难,不推荐,以后深造的时候可以多学学
class Countlist:
def __init__(self,*args):
self.values = [a for a in args]
self.count ={}.fromkeys(range(len(self.values)),0)
def __len__(self):
return len(self.values)
def __getitem__(self, a):
self.count[a] += 1
return self.values[a]
c1 = Countlist(1,3,3,5,7,9)
c2 = Countlist(2,4,6,8,10)
c1[2]
c1[3] + c1[2]
print(c1.values[2])
print(c1.count)
print(c1.values)
结束