判断一个文件里面的单词出现多少次

import this
import collections
import os
# s=0
#a.txt是你要查询单词个数的文件名
def cal(filename='a.txt'):
    with open(filename, 'r') as f:
        data = f.read()
    data = data.lower()
    # 替换除了n't这类连字符外的所有非单词字符和数字字符
    datalist = re.split(r'[\s\n]+', data)
    return Counter(datalist).most_common()
    # print(length.datalist)


if __name__ == '__main__':
    dic = cal()
    for i in range(len(dic)):
        print('%15s  ---->   %3s' % (dic[i][0], dic[i][1]))

你可能感兴趣的:(判断一个文件里面的单词出现多少次)