2016-08-03 9 views
0

NLTKで実際に非常に簡単に解決できる問題があります。私は私の問題の解決策を見つけましたが、そこに彼らはNLTK使用しないでください。NLTK Python 3を使って特定のBigramを見つける

how can I count the specific bigram words?

それはNLTK機能でそれを行うことは可能ですか?私はfood_low.txtから単語がcleaned2.txtに表示される頻度を数えています

food = open("food_low.txt") 
lines = food.read().split(',')[:-1] 

raw = wordlists.words("cleaned2.txt") 
fdist = nltk.FreqDist(w.lower() for w in raw) 

with io.open('nltk1.txt', 'w', encoding="utf-8") as h: 
    for m in lines: 
     if fdist[m] > 0: 
      print(m + ':', fdist[m], end=' ', file = h) 

は、ここに私のコードです。私の問題は、food_low.txtにいくつかのバイグラムの言葉があり、数えられていないことです。どのようにしてバイグラムを数えることができますか?

答えて

0

NLTKなしで、正規表現(re)を使用してunigramとbigramを数えることができます。今、あなたは、2つの別々の計算を必要としませんが、re.findall()と一度にそれを行うことができます。nltk1.txtの

import re 
import codecs 

# List of words and a sentence 
l = ['cow', 'dog', 'hot dog', 'pet candy'] 
s = 'since the opening of the bla and hot dog in the hot dog cow' 

# Make your own fdist 
fdist = {} 
for m in l: 
    # Find all occurrences of m in l and store the frequency in fdist[m] 
    fdist[m] = len(re.findall(m, s)) 

# Write the wordcounts for each word to a file (if fdist[m] > 0) 
with codecs.open('nltk1.txt', 'w', encoding='utf8') as out: 
    for m in l: 
     if fdist[m] > 0: 
      out.write('{}:\t{}\n'.format(m, fdist[m])) 

内容:

cow: 1 
dog: 2 
hot dog: 2 

注:NLTKを使用したい場合は、this answer might fulfill your needs

関連する問題