def count_word(filename): word_dic = {} num = 1 with open(filename,mode='r',encoding='utf-8') as f: word_str = ''.join(f.read()) #用空把所有的单词拼接起来 word_lst = word_str.split() #把拼接起来的字符串,通split做成单词列表 for word in word_lst: if word not in word_dic: #如果单词不在字典中,就在字典中添加这个单词的key,并赋值为1 word_dic[word] = num else: #否则单词在典中,就把对应单词key的值加1 word_dic[word] += 1 return word_dic ret = count_word(r'c:/file') print(ret)