计算python中的唯一单词

2024-03-28 21:41:23 发布

您现在位置:Python中文网/ 问答频道 /正文

直接说来,我的代码是:

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文件),但我不知道如何计算。有人能帮我吗?


Tags: 代码fromimportreporttxtdefwithopen
3条回答

在Python中计算对象的最佳方法是使用^{}类,该类是为此目的而创建的。它的行为类似于Python dict,但在计算时使用起来更容易一些。您只需传递一个对象列表,它就会自动为您计算这些对象。

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

此外,Counter还有一些有用的方法,如大多数常用方法,请访问documentation了解更多信息。

Counter类的一个方法也是非常有用的,那就是update方法。通过传递对象列表实例化计数器后,可以使用update方法执行相同操作,并且它将继续计数,而不删除对象的旧计数器:

>>> 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})

如果要计算每个唯一单词的数量,请使用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}
print len(set(w.lower() for w in open('filename.dat').read().split()))

Reads the entire file into memory, splits it into words using whitespace, converts each word to lower case, creates a (unique) set from the lowercase words, counts them and prints the output

相关问题 更多 >