天天看点

python练习 0004

第 0004 题: 任一个英文的纯文本文件,统计其中的单词出现的个数。

思路:

1.打开文本文件

2.读取文本文件内容,去除换行符以及按照空格和逗号分隔将单词加入list中

3.使用collections中Counter来统计单词个数

import collections
import re

def calwords(path):
    word = []
    with open(path) as file:
        data = file.readlines()
    for line in data:
        word += re.split(' |,',line.strip('\n'))
    print(collections.Counter(word))


if __name__ == '__main__':
    calwords('e://code.txt')