1.場景
在很久很久以前,有一個(gè)王后。
有一天,她在讀《A?Tale?of?Two?Cities》q2.txt:

A Tale of Two Cities
王后覺得這段文字很有意思,很有規(guī)律。于是,她想統(tǒng)計(jì)一下每個(gè)詞都出現(xiàn)了多少次。
效果如a2.txt:

目標(biāo)文件
我們來幫她實(shí)現(xiàn)。
2.代碼
python版本:v3.7.3
用法: python wordsCount.py q2.txt a2.txt
#wordsCount.py
#2020.03.11
import sys
from collections import Counter
def words_count(in_file, out_file):
#用列表解析一次性將文件所有內(nèi)容讀入,文件大于1GB時(shí)最好不要這么做
#文件最好使用utf-8讀取和寫入
in_lines = [line for line in open(in_file, "r", encoding="utf-8")]
#用列表解析的方式得到所有行中的word
words_list = []
[words_list.extend(item.strip().split()) for item in in_lines]
#用Collections包里的Counter方法直接統(tǒng)計(jì),得到1個(gè)可遍歷的對象
words_counter = Counter(words_list).most_common()
#遍歷上面的對象,準(zhǔn)備輸出的列表
out_lines = [item[0]+"\t"+str(item[1])+"\n" for item in words_counter]
#直接寫入list
with open(out_file, "w", encoding="utf-8") as fw:
fw.writelines(out_lines)
if __name__ == "__main__":
#從控制臺cmd接收參數(shù)列表
args = sys.argv
in_file = args[1]
out_file = args[2]
words_count(in_file, out_file)
3.討論
王后: 如果我只想要詞數(shù)最多的前10個(gè)詞呢?
作者:
只需要將第14行改為
words_counter = Counter(words_list).most_common(10)即可
王后:it和It是同一個(gè)詞,能不能算在一起,即統(tǒng)計(jì)時(shí)不區(qū)分大小寫?
作者:
最好區(qū)分大小寫,不區(qū)分的話輸出的時(shí)候就不能確定是輸出
it還是It呢?