直接来说,到目前为止我的代码是这样的:
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
我想添加一个代码来计算模式中的唯一单词(此路径中有 42 个 txt 文件),但我不知道如何操作。谁能帮帮我?
最佳答案
在 Python 中计算对象的最佳方法是使用 collections.Counter
类,这是为此目的而创建的。它的作用类似于 Python 字典,但在计数时使用起来更容易一些。您只需传递一个对象列表,它就会自动为您计数。
>>> from collections import Counter
>>> c = Counter(['hello', 'hello', 1])
>>> print c
Counter({'hello': 2, 1: 1})
计数器还有一些有用的方法,比如most_common,访问documentation了解更多。
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})
关于python - 计算 python 中的唯一单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11899878/