计算python中的唯一单词

时间:2012-08-10 10:33:25

标签: 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

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

3 个答案:

答案 0 :(得分:7)

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

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

此外,Counter还有一些有用的方法,例如most_common,请访问documentation了解详情。

Counter类的一个方法也是非常有用的是update方法。在通过传递对象列表实例化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})

答案 1 :(得分:2)

print len(set(w.lower() for w in open('filename.dat').read().split()))
  

将整个文件读入内存,使用将其拆分为单词   空白,转换       每个单词为小写,从小写单词创建(唯一)集合,计算它们       并打印输出

答案 2 :(得分:0)

如果您想获得每个唯一单词的计数,请使用dicts:

words = ['Hello', 'world', 'world']
count = {}
for word in words :
   if word in count :
      count[word] += 1
   else:
      count[word] = 1

你会得到字典

{'Hello': 1, 'world': 2}
相关问题