#### 统计一个文本文件里各单词出现的次数 #### 单词简单定义为空白字符分隔的连续非空白字符 def textstat (infname, statfile): worddict = {} textfile = open(infname) for line in textfile: wordlist = line.split() for word in wordlist: if word in worddict: worddict[word] += 1 else: worddict[word] = 1 textfile.close() outfile = open(statfile, "w") for word in sorted(worddict.keys()): outfile.write(word + ", " + str(worddict[word]) + "\n") outfile.close() #### end of textstat if __name__ == "__main__": textstat("sun1.txt", "sun-data.txt") print("Finished, and the result is in sun-data.txt.")