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萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章