2017-12-19 6 views
0

ファイルに保存されているngramを読みたい。そして、それはそれと一致するならば、ngram.let私はこれらのバイグラムを持っていると言うと、それを置き換える私のコーパス内の個々のトークンでそれらngramsの各単語を一致:ファイルからngramsを読み込んでトークンと照合する方法

painful punishment 
worldly life 
straight path 
Last Day 
great reward 
severe punishment 
clear evidence 

を私は何をしたいかは、最初のバイグラムを読み取ることで、それを分割して、そのトークンと一致するコーパス内のトークンを「苦痛」とし、次のトークンに移動し、それが「罰」であればbigramの次の単語とマッチさせ、苦痛を伴う刑罰 "である。私はこれを行う方法を知らない。私はこの論理をcode.ifに変換したいと思っています。私が本当にとても感謝してくれる人なら誰でも助けてくれるはずです。

答えて

0

まず、これはStackOverflow(宿題の質問のように聞こえる)の質問ではありません。 Googleを介してこれを達成するためのさまざまな方法を簡単に識別できます。私はウォームアップする必要があるように私は、しかし、あなたに1つのソリューションを提供します:

# -*- coding: utf-8 -*- 

import traceback, sys, re 

''' 
Open the bigrams file and load into an array. 
Assuming bigrams are cleaned (else, you can do this using method below). 
''' 
try: 
    with open('bigrams.txt') as bigrams_file: 
     bigrams = bigrams_file.read().splitlines() 
except Exception: 
    print('BIGRAMS LOAD ERROR: '+str(traceback.format_exc())) 
    sys.exit(1) 

test_input = 'There is clear good evidence a great reward is in store.' 

''' 
Clean input method. 
''' 
def clean_input(text_input): 
    text_input = text_input.lower() 
    text_input = text_input.strip(' \t\n\r') 
    alpha_num_underscore_only = re.compile(r'([^\s\w_])+', re.UNICODE) 
    text_input = alpha_num_underscore_only.sub(' ', text_input) 
    text_input = re.sub(' +', ' ', text_input) 
    return text_input.strip() 

test_input_words = test_input.split() 
test_input_clean = clean_input(test_input) 
test_input_clean_words = test_input_clean.split() 

''' 
Loop through the test_input bigram by bigram. 
If we match one, then increment the index to move onto the next bigram. 
This is a quick implementation --- you can modify for efficiency, and higher-order n-grams. 
''' 
output_text = [] 
skip_index = 0 
for i in range(len(test_input_clean_words)-1): 
    if i >= skip_index: 
     if ' '.join([test_input_clean_words[i], test_input_clean_words[i+1]]) in bigrams: 
      print(test_input_clean_words[i], test_input_clean_words[i+1]) 
      skip_index = i+2 
      output_text.append('TOKEN_'+'_'.join([test_input_words[i], test_input_words[i+1]]).upper()) 
     else: 
      skip_index = i+1 
      output_text.append(test_input_words[i]) 
output_text.append(test_input_words[len(test_input_clean_words)-1]) 

print(' '.join(output_text)) 

入力:

There is clear good evidence a great reward is in store. 

を出力:

There is clear good evidence a TOKEN_GREAT_REWARD is in store. 
+0

が私のファイルをreplying.inためにあなたをとても感謝していますbigramsだけでなく、ngrams.bigrams、trigramsなどがあります.iはすでに私のコーパスをきれいにしました。これは家事ではありません。実際に私は英語で作業していないので、いくつかのソリューションを実装するのは難しいです。私は思っていた解決策を試しました.iはngramsとunigramsの両方の頻度を計算し、ファイル内に理解することが難しかった – user3778289

+0

ありがとうございました。 – user3778289

関連する問題