2

nltkを使用してランダムな文を生成する必要があります。ただし、text.generate()はトリグラムを含む文しか提供しないようです。これを拡張して、バイグラムだけでなくユニグラムも含めることができる方法はありますか?

私の現在のコードは次のとおりです。

exclude = set(string.punctuation)
ln = ''.join(ch for ch in ln if ch not in exclude)


words = nltk.word_tokenize(ln)
my_bigrams = nltk.bigrams(words)
my_trigrams = nltk.trigrams(words)


tText = Text(words)
tText1 = Text(my_bigrams)
tText2 = Text(my_trigrams)
print tText.generate()
print tText1.generate()
print tText2.generate()

generate()関数の変更:

def generate(self, length=100, c=3):
    """
    Print random text, generated using a trigram language model.

    :param length: The length of text to generate (default=100)
    :type length: int
    :seealso: NgramModel
    """
    if '_trigram_model' not in self.__dict__:
        print "Building ngram index..."
        estimator = lambda fdist, bins: LidstoneProbDist(fdist, 0.2)
        self._trigram_model = NgramModel(c, self, estimator=estimator)
    text = self._trigram_model.generate(length)
    print tokenwrap(text)
4

1 に答える 1

1

コードを読んだ後、いくつかの考慮事項があります。

ユニグラムとバイグラムを使用する場合は、生成関数を自分で作成する必要があります。開始点としてgenerate()のソースを使用するのは簡単なはずです。

nltk.Textクラスに動的にアタッチして、オブジェクトで使用できるようにすることもできますnltk.Text.generate_with_ngrams= my_generation_function(最初の引数として「self」を含めることを忘れないでください)。

于 2012-11-18T05:22:12.960 に答える