计算python中的唯一单词

roc*_*and 4 python word-count

直接,我的代码到目前为止是这样的:

from glob import glob
pattern = "D:\\report\\shakeall\\*.txt"
filelist = glob(pattern)
def countwords(fp):
    with open(fp) as fh:
        return len(fh.read().split())
print "There are" ,sum(map(countwords, filelist)), "words in the files. " "From directory",pattern
Run Code Online (Sandbox Code Playgroud)

我想添加一个代码来计算模式中的唯一单词(此路径中有42个txt文件),但我不知道如何.有谁能够帮我?

Ros*_*nko 7

在Python中计算对象的最佳方法是使用collections.Counter为此目的而创建的类.它的行为类似于Python dict,但在计算时更容易使用.您只需传递一个对象列表,它就会自动为您计算.

>>> from collections import Counter
>>> c = Counter(['hello', 'hello', 1])
>>> print c
Counter({'hello': 2, 1: 1})
Run Code Online (Sandbox Code Playgroud)

Counter还有一些有用的方法,比如most_common,访问文档以了解更多信息.

Counter类的一种方法也可以是非常有用的更新方法.在通过传递对象列表实例化Counter之后,您可以使用更新方法执行相同操作,并且它将继续计数而不会丢弃对象的旧计数器:

>>> from collections import Counter
>>> c = Counter(['hello', 'hello', 1])
>>> print c
Counter({'hello': 2, 1: 1})
>>> c.update(['hello'])
>>> print c
Counter({'hello': 3, 1: 1})
Run Code Online (Sandbox Code Playgroud)