天天看點

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')