用python统计文件夹下文本中的单词个数,每个文本中包含一个单词:
文件夹路径为path,返回字典word_dic
def wordCounter(path):
word_dic = {}
for filename in os.listdir(path):
filepath = os.path.join(path,filename)
#print filepath
#get the content
f = open(filepath , "r")
content = f.read()
f.close()
#counter
if content not in word_dic:
word_dic[content] = 1
else :
word_dic[content] += 1
#print word_dic
return word_dic
检查路径是否存在:
if not os.path.exists(filename): print("ERROR:file not exit . " )