最简洁的方法是使用Python提供的工具。
from future_builtins import map # only on Python 2from collections import Counterfrom itertools import chaindef countInFile(filename): with open(filename) as f: return Counter(chain.from_iterable(map(str.split, f)))
而已。
map(str.split,f)使生成器
list从每一行返回s个单词。包装
chain.from_iterable将其转换为单个生成器,一次生成一个单词。
Counter接受一个可迭代的输入,并计算其中的所有唯一值。最后,您
return是一个类似
dict的对象(a
Counter),用于存储所有唯一单词及其计数,并且在创建期间,您一次只存储一行数据和总计数,而不是一次存储整个文件。
从理论上讲,在Python
2.7和3.1上,您可以自己更好地循环使用链结结果,并使用
dict或
collections.defaultdict(int)进行计数(因为
Counter在Python中实现,在某些情况下会使其变慢),但让
Counter工作更简单以及更多自我记录(我的意思是,整个目标都在计算,因此请使用
Counter)。除此之外,在CPython(参考解释器)3.2和更高版本上,
Counter还具有C级加速器,用于对可迭代的输入进行计数,其运行速度比纯Python中编写的任何代码都要快。
更新: 您似乎想删除标点符号并且不区分大小写,所以这是我以前的代码的一种变体,它可以做到:
from string import punctuationdef countInFile(filename): with open(filename) as f: linewords = (line.translate(None, punctuation).lower().split() for line in f) return Counter(chain.from_iterable(linewords))
你的代码的运行速度要慢得多,因为它创建和销毁许多小型
Counter和
set对象,而不是
.update-ing单
Counter每行(其中,而稍比我在更新的代码块给速度较慢,至少会在比例因子算法类似的一次)。



