私は、マルコフ連鎖を使用せずにランダムテキストジェネレーターに取り組んでおり、現在、あまり問題なく動作しています。まず、私のコードフローは次のとおりです。
入力として文を入力 - これはトリガー文字列と呼ばれ、変数に割り当てられます -
トリガー文字列で最も長い単語を取得する
Project Gutenberg データベースで、この単語 -regardless of uppercase Lowercase- を含む文を検索します。
ステップ 3 で話した単語を含む最も長い文を返します
ステップ 1 とステップ 4 の文を一緒に追加します。
ステップ 4 のセンテンスを新しい「トリガー」センテンスとして割り当て、プロセスを繰り返します。2番目の文で最も長い単語を取得し、そのように続ける必要があることに注意してください-
そして、ここに私のコードがあります:
import nltk
from nltk.corpus import gutenberg
from random import choice
triggerSentence = raw_input("Please enter the trigger sentence: ")#get input str
longestLength = 0
longestString = ""
listOfSents = gutenberg.sents() #all sentences of gutenberg are assigned -list of list format-
listOfWords = gutenberg.words()# all words in gutenberg books -list format-
while triggerSentence:
#so this is run every time through the loop
split_str = triggerSentence.split()#split the sentence into words
#code to find the longest word in the trigger sentence input
for piece in split_str:
if len(piece) > longestLength:
longestString = piece
longestLength = len(piece)
#code to get the sentences containing the longest word, then selecting
#random one of these sentences that are longer than 40 characters
sets = []
for sentence in listOfSents:
if sentence.count(longestString):
sents= " ".join(sentence)
if len(sents) > 40:
sets.append(" ".join(sentence))
triggerSentence = choice(sets)
print triggerSentence
私の懸念は、ループがほとんどの場合、同じ文が何度も何度も印刷されるポイントに到達することです。最長の単語を持つのは最長の文だからです。同じ文が何度も繰り返されることに対抗するために、私は次のことを考えました。
*現在の文の最も長い単語が最後の文と同じ場合は、現在の文からこの最も長い単語を削除して、次に長い単語を探します。
このためにいくつかの実装を試みましたが、リストとリストのリストが含まれているため、上記の解決策を適用できませんでした-gutenbergモジュールの単語と文が原因です. 2 番目に長い単語を見つける方法について何か提案はありますか? NLTK の Gutenberg モジュールの .sents() および .words() 関数はそれぞれリストとリストのリストを生成するため、単純な文字列入力の解析ではこれを行うことができないようです。前もって感謝します。