Python每日一練(1):計算文件夾內各個文章中出現次數最多的單詞


#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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM