2016-03-23 4 views
2

は私が簡単で、最も一般的な単語を取得することができます:テキスト中の単語の頻度を取得する方法は、それらの品詞に依存しますか?

stopwords = set(nltk.corpus.stopwords.words('english'))  
tagged_words = nltk.word_tokenize(text) 
tagged_words = nltk.pos_tag(tagged_words) 

# Remove single-character tokens (mostly punctuation) 
tagged_words = [tagged_word for tagged_word in tagged_words if len(tagged_word[0]) > 1] 

# Remove numbers 
tagged_words = [tagged_word for tagged_word in tagged_words if not tagged_word[0].isnumeric()] 

# Remove stopwords 
if remove_stopwords: 
    tagged_words = [tagged_word for tagged_word in tagged_words if tagged_word[0] not in stopwords] 

# Dark magic 
lemmatizer = nltk.stem.WordNetLemmatizer() 
words = [] 
for tagged_word in tagged_words: 
    pos = wordnet_pos_code(tagged_word[1]) 
    # Ignoring all words, except nouns, verbs, adjectives and adverbs 
    if pos is not None: 
     words.append({'word':lemmatizer.lemmatize(tagged_word[0], pos=pos), 'pos':tagged_word[1]}) 

# Calculate frequency distribution 
fdist = nltk.FreqDist(words) 

# Return top % words_count % words 
res = [] 
for word, frequency in fdist.most_common(words_count): 
    word_dict = {} 
    word_dict['word'] = word 
    word_dict['count'] = frequency 
    res.append(word_dict) 
return res 

しかし、私は、人の名前や色などの「ブラウン」と「ブラウン」のようないくつかの単語を持って、彼らは同じではありません。さて、私は大文字でそれらを確認することができます。しかし、私が何かを得る場合:

ブラウンは単なる色ではありません。ブラウンはライフスタイルの一部です。そして、ブラウン氏は私に同意するはずです。

したがって、nltkは品詞解析をかなりうまく行います。しかし、どのように私は最も一般的な言葉を得ることが品詞に依存していますか?

答えて

0

タプルの配列として単語と位置を収集し、その頻度をFreqDistで取得しました。

これで、配列に並べ替えることができます。

res = [] 
for word, frequency in fdist.most_common(words_count): 
    word_dict = {} 
    word_dict['word'] = word 
    word_dict['count'] = frequency 
    res.append(word_dict) 
return res 
0

wordsをキーにCounterオブジェクトを値として使用して、defaultdictを試してみてください。内側のCounterの場合、キーはPOSであり、値はワードが与えられたPOSのカウントです。

>>> from collections import defaultdict, Counter 
>>> from nltk.corpus import brown 
>>> corpus_counts = defaultdict(Counter) 
>>> for word, tag in brown.tagged_words(): 
...  if word in corpus_counts: 
...    corpus_counts[word][tag] +=1 
...  else: 
...    corpus_counts[word] = Counter({tag:1}) 
... 
>>> 
>>> corpus_counts['run'] 
Counter({u'VB': 122, u'NN': 52, u'VBN': 31, u'VBD': 1}) 
>>> corpus_counts['run']['VB'] 
122 
関連する問題