python学习--记词器程序
#!/usr/bin/env python3 # -*- coding: utf-8 -*- #CalHamlet.py def getText(): txt = open("install.sh", "r").read() #读取整个文件 txt = txt.lower() #大写全部转成小写 for ch in '!"\'.,#$%&()*+-/:;<=>?@[\\]^_`{|}~': txt = txt.replace(ch, " ") #特殊字符全用空格替代 return txt #返回文件 hamletTxt = getText() #调用处理函数 words = hamletTxt.split() #取消掉所有空格,放入到列表words中 #print(words) counts = {} for word in words: counts[word] = counts.get(word,0) + 1 #将列表转换成字典,键值用键的个数代替 #print(counts) # print(counts[word]) items = list(counts.items()) #将字典转换为列表。 #print(items) items.sort(key = lambda x:x[1], reverse = True) #以第2列进行排序 for i in range(10): word, count = items[i] print("{0:<10} {1:>5}".format(word, count))