2017-04-23 4 views
0

いくつかの文で連鎖を見つけて適用する必要があります。文は文字列のリストに格納されます。今、ただ一つの文に集中しましょう。ここで は例です:バイグラムのlistoからコロケーションをPythonのNLTKで適用する

sentence = 'I like to eat the ice cream in new york' 

は、ここで私は終わりにしたいものです。

sentence_final = 'I like to eat the ice_cream in new_york' 

私はコロケーションを見つけるために、PythonのNLTKを使用していると私はすべての可能を含むセットを作成することができますよ私が持っているすべての文章のコロケーション。ここ はセットの例です:

set_collocations = set([('ice', 'cream'), ('new', 'york'), ('go', 'out')]) 

それは現実には明らかに大きいです。

私は新しい関数を返す必要があります次の関数、上記のように修正作成:

def apply_collocations(sentence, set_colloc): 
    window_size = 2 
    words = sentence.lower().split() 
    list_bigrams = list(nltk.bigrams(words)) 
    set_bigrams=set(list_bigrams) 
    intersect = set_bigrams.intersection(set_colloc) 
    print(set_colloc) 
    print(set_bigrams) 
    # No collocation in this sentence 
    if not intersect: 
     return sentence 
    # At least one collocation in this sentence 
    else: 
     set_words_iters = set() 
     # Create set of words of the collocations 
     for bigram in intersect: 
      set_words_iters.add(bigram[0]) 
      set_words_iters.add(bigram[1]) 
     # Sentence beginning 
     if list_bigrams[0][0] not in set_words_iters: 
      new_sentence = list_bigrams[0][0] 
      begin = 1 
     else: 
      new_sentence = list_bigrams[0][0] + '_' + list_bigrams[0][1] 
      begin = 2 

     for i in range(begin, len(list_bigrams)): 
      print(new_sentence) 
      if list_bigrams[i][1] in set_words_iters and list_bigrams[i] in intersect: 
       new_sentence += ' ' + list_bigrams[i][0] + '_' + list_bigrams[i][1] 
      elif list_bigrams[i][1] not in set_words_iters: 
       new_sentence += ' ' + list_bigrams[i][1] 
     return new_sentence 

2に質問:

  • をこれにより最適化された方法はありますか?
  • 私はNLTKで少し劣っているので、特定のテキストにコロケーションを適用する「直接的な方法」があるかどうか教えてもらえますか?私がコロケーションを考慮するバイグラムを見つけたら、私の文章を修正するための機能(または速い方法)がありますか?

答えて

1

あなたは単にあなたの設定コロケーション内の各要素に対して、「X_Y」で文字列「X Y」に置き換えることができます。

def apply_collocations(sentence, set_colloc): 
    res = sentence.lower() 
    for b1,b2 in set_colloc: 
     res = res.replace("%s %s" % (b1 ,b2), "%s_%s" % (b1 ,b2)) 
    return res 
関連する問題