统计文本中每个单词出现的次数

# coding:utf-8

import re

def CountNum(filepath):

    myfile = open(filepath, 'r')
    content = myfile.read()
    CountDict = {}
    pattern = '[,.\s]\s*'
    words = re.split(pattern, content)
    for word in words:
        if word not in CountDict and word.isalpha():
            CountDict[word.lower()] = 1
        elif word in CountDict:
            CountDict[word.lower()] += 1

    result = sorted(zip(CountDict.keys(), CountDict.values()))
    for i, j in result:
        print (i, j)

if __name__ == '__main__':
    CountNum('count.txt')
其中:\s匹配任何空格字符,与[\n\t\r\v\f]相同
关于zip的使用请参考http://www.cnblogs.com/frydsh/archive/2012/07/10/2585370.html
posted @ 2017-10-24 17:27  milian0711  阅读(1152)  评论(0编辑  收藏  举报