用python統計多個文字中你想統計的單詞
阿新 • • 發佈:2019-02-07
import collections #計數器 import os import string path = "/Users/U/workspace/python learning/show-me-the-code/0006/diary/" #diary dir dir = os.listdir(path) #讀取目錄 sum = 0 #單詞總數 wanna = 'I' #想要統計的單詞 for file in dir: #遍歷目錄 with open(path + file) as diary: list = diary.read().split(' ') #單詞以空格分開 newlist = [word.translate(word.maketrans("","",string.punctuation)) for word in list] #幹掉所有標點符號 #用maketrans建立一個對映表 translate根據對映錶轉化字串 sum += int(collections.Counter(newlist)[wanna]) #統計所以日記中單詞"I"的個數 #print(newlist) #test newlist print('%s:%d' % (wanna,sum))