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