#coding:utf-8import os,repath = 'test'files = os.listdir(path)def count_word(words): dic = {} max = 0 marked_key = '' #計算每個單詞出現的次數 for ...
#coding:utf-8 import os,re path = 'test' files = os.listdir(path) def count_word(words): dic = {} max = 0 marked_key = '' #計算每個單詞出現的次數 for word in words: if dic.has_key(word) is False: dic[word] = 1 else: dic[word] = dic[word] +1 #每個字典的值之間做比較,得出最大的那個數字 for key,value in dic.items(): if dic[key] > max: max = dic[key] marked_key = key #跳出for迴圈列印出單詞和單詞出現的次數 print(marked_key,max) for f in files: with open(os.path.join(path,f)) as diary: words = re.findall("[a-zA-Z]+'*-*[a-zA-z]", diary.read()) count_word(words)
#has_key(key) : 函數用於判斷鍵是否存在於字典中,如果鍵在字典dict里返回true,否則返回false。這裡用於判斷字典內的鍵是否出現過。
這個是Git上的Python每日一聯小項目,我就不提交到那邊了,寫到這裡來。
項目地址:https://github.com/Yixiaohan/show-me-the-code