練習006

第 0006 題:你有一個目錄,放了你一個月的日記,都是 txt,爲了避免分詞的問題,假設內容都是英文,請統計出你認爲每篇日記最重要的詞。

代碼006.py

#!/usr/bin python 
#coding:utf-8
'''
Created on 2016年4月25日
@author: zxc
'''
import os,re
from collections import Counter
FILE_PATH=r'F:\Python\txt'
stop_word = ['the', 'in', 'of', 'and', 'to', 'has', 'that', 's', 'is', 'are', 'a', 'with', 'as', 'an','for']
def getCounter(i):
    pattern = r'[A-Za-z]+|\$?\d+%?$'
    print i 
    i = os.path.join(FILE_PATH,i)
    print i 
    f=open(i,'r')
    r = re.findall(pattern, f.read())
    return Counter(r)    

def run(FILE_PATH):  
    total_counter = Counter()
    for i in os.listdir(FILE_PATH):
        if os.path.splitext(i)[1] == '.txt':
            #print os.path.splitext(i)[1] 
            total_counter += getCounter(i)
    for i in stop_word:
        total_counter[i] = 0
    print total_counter.most_common()[0][0]            

if __name__=="__main__":
    run(FILE_PATH)

( 寫於2016年4月27日,http://blog.csdn.net/bzd_111

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章