Python实现计算一段文本中每个单词出现的次数

看实验楼的课程,有一个小练习,做了一下。要求用Python实现计算一段文本中每个单词出现的次数。

sentence = 'hello world nihao world hey hello java world hi python yeoman word'

#先把字符串分割成单个单词列表
list1 = sentence.split() 
#['hello', 'world', 'nihao', 'world', 'hey', 'hello', 'java', 'world', 'hi', 'python', 'yeoman', 'word']
print list1 

#把列表转为结合,为了去除重复的项
set1 = set(list1)   
#set(['java', 'python', 'word', 'nihao', 'hey', 'yeoman', 'hi', 'world', 'hello'])
print set1  

#把集合转为列表,集合元素没有顺序,没有索引属性,而列表有
list2 = list(set1)  
#['java', 'python', 'word', 'nihao', 'hey', 'yeoman', 'hi', 'world', 'hello']
print list2 

#新建一个空的字典
dir1 = {}

for x in range(len(list2)): 
    dir1[list2[x]] = 0  #字典值初始为0
    for y in range(len(list1)):
        if list2[x] == list1[y]:
            dir1[list2[x]] += 1

#{'word': 1, 'python': 1, 'nihao': 1, 'hey': 1, 'hello': 2, 'hi': 1, 'world': 3, 'java': 1, 'yeoman': 1}
print dir1  
发布了116 篇原创文章 · 获赞 132 · 访问量 45万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章