-1

I'm attempting to write a script that counts the number of occurences of a given list of tokens in a collection of files. So far I have the following:

for text in posts:
   words = wordpunct_tokenize (text)
   tags = nltk.pos_tag (words)
   list_tags=defaultdict(int)
   for a,b in tags:
      tags3.append(b)
   for t in tags3:
      if t in tags_list:
          list_tags[t]+=1
   print list_tags

problem is that the program does not purge the tokens if found in the previous post, and is just counting up per post. At the last post it claims to have found 70.000 occurences of a given token in a post of 500 words.

Does anyone have an idea what I am doing wrong?

4

1 に答える 1

4

リストにタプルを追加しました:

list_words.append(("foo", "bar", "tiger")) 

text個々の単語に分割するため、 for が の3 つの単語を含むタプルは決してありません。そのため、カウントが 70.000 に達するというあなたの主張は真実ではありません。コードは、示されているように、空の辞書しか提供しません。wordsw in list_wordsTruelist_words2

リストを直接定義するだけです:

list_words = ["foo", "bar", "tiger"]

またはさらに良いのは、set高速メンバーシップ テストに a を使用することです。

set_words = {"foo", "bar", "tiger"}

collections.Counter()代わりに次のコードを使用すると、コードが読みやすくなります。

from collections import Counter    

set_words = {"foo", "bar", "tiger"}

for text in posts:
    list_words2 = Counter(word for word in text.split() if word in set_words)
    print list_words2

変更された質問を実際のコードで更新します。

tags3リストをクリアせずに追加することにより、新しいタグ付き単語でリストを更新しています。text処理するたびにtags3成長しますが、ループ内の反復ごとtags3 に最初から処理します。あなたの 70.000 は階乗数です。最初に 400 個のトークンを処理し、次にさらに 300 個のタグを処理して合計 700 個のタグを処理し、さらに 100 個の単語を処理するので、tags800 回以上ループします。

tags3この問題を回避するには (ループtags3 = [] など)、クリアするか、直接ループしtagsまったく追加しないようにすることをお勧めします。

for text in posts:
   words = wordpunct_tokenize (text)
   tags = nltk.pos_tag (words)
   list_tags = Counter(b for a, b in tags if b in tags_list)
   print list_tags

tags_listそれが本当にセットであることを確認してください。そうでない場合、テストはすべてのタグb in tags_listの要素をループする必要があります。tags_list

于 2013-05-15T16:50:46.890 に答える