5

直接的には、これまでの私のコードは次のとおりです。

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 ファイル) から一意の単語をカウントするコードを追加したいのですが、方法がわかりません。誰でも私を助けることができますか?

4

3 に答える 3

8

Python でオブジェクトを数える最良の方法はcollections.Counter、その目的のために作成されたクラスを使用することです。これは Python dict のように機能しますが、数を数えるときに使用する方が少し簡単です。オブジェクトのリストを渡すだけで、自動的にカウントされます。

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

また、Counter には most_common などの便利なメソッドがいくつかあります。詳細については、ドキュメントを参照してください。

非常に便利な Counter クラスのメソッドの 1 つは update メソッドです。オブジェクトのリストを渡して Counter をインスタンス化した後、 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})
于 2012-08-10T10:43:09.523 に答える
2
print len(set(w.lower() for w in open('filename.dat').read().split()))

ファイル全体をメモリに読み込み、空白を使用して単語に分割し、各単語を小文字に変換し、小文字の単語から (一意の) セットを作成し、それらをカウントして出力を出力します。

于 2012-08-10T10:43:17.073 に答える
0

一意の各単語の数を取得する場合は、辞書を使用します。

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

そして、あなたは辞書を取得します

{'Hello': 1, 'world': 2}
于 2012-08-10T10:36:32.527 に答える