私はランダムテキストジェネレーターに取り組んでいます-マルコフ連鎖を使用せずに-そして現在それはあまり多くの問題なしで動作します-実際には私の基準によってかなりの量のランダムな文を生成しますが、多くの文の繰り返しを防ぐためにさらに正確にしたいと思いますできるだけ-。まず、私のコードフローは次のとおりです。
入力として文を入力します-これはトリガー文字列と呼ばれ、変数に割り当てられます-
トリガー文字列で最長の単語を取得する
すべてのProjectGutenbergデータベースで、この単語を含む文を検索します-大文字と小文字に関係なく-
手順3で話した単語を含む最長の文を返します
ステップ1とステップ4の文を一緒に追加します
手順4の文を新しい「トリガー」文として割り当て、プロセスを繰り返します。私は2番目の文で最も長い単語を取得し、そのように続ける必要があることに注意してください-
そしてここに私のコードがあります:
import nltk
from nltk.corpus import gutenberg
from random import choice
import smtplib #will be for send e-mail option later
triggerSentence = raw_input("Please enter the trigger sentence: ")#get input str
longestLength = 0
longestString = ""
longestLen2 = 0
longestStr2 = ""
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:#run the loop so long as there is a trigger sentence
sets = []
sets2 = []
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
for sentence in listOfSents:
if sentence.count(longestString):
sents= " ".join(sentence)
if len(sents) > 40:
sets.append(" ".join(sentence))
triggerSentence = choice(sets)
print triggerSentence #the first sentence that comes up after I enter input-
split_str = triggerSentence.split()
for apiece in triggerSentence: #find the longest word in this new sentence
if len(apiece) > longestLen2:
longestStr2 = piece
longestLen2 = len(apiece)
if longestStr2 == longestString:
second_longest = sorted(split_str, key=len)[-2]#this should return the second longest word in the sentence in case it's longest word is as same as the longest word of last sentence
#print second_longest #now get second longest word if first is same
#as longest word in previous sentence
for sentence in listOfSents:
if sentence.count(second_longest):
sents = " ".join(sentence)
if len(sents) > 40:
sets2.append(" ".join(sentence))
triggerSentence = choice(sets2)
else:
for sentence in listOfSents:
if sentence.count(longestStr2):
sents = " ".join(sentence)
if len(sents) > 40:
sets.append(" ".join(sentence))
triggerSentence = choice(sets)
print triggerSentence
私のコードによると、トリガーセンテンスを入力すると、入力したトリガーセンテンスの最長の単語を含む別の単語を取得する必要があります。次に、この新しい文がトリガー文になり、最長の単語が選択されます。ここで問題が発生することがあります。私が配置したコード行(47行目から最後まで)にも関わらず、アルゴリズムは、2番目に長い単語を探すのではなく、続く文の中で同じ最長の単語を選択できることに気付きました。
例えば:
トリガー文字列="スコットランドはいい場所です。"
文1=-これはスコットランドという単語が含まれるランダムな文です-
さて、これは時々私のコードで問題が発生する可能性がある場所です-それが文2、942、またはzillionなどで発生するかどうかは関係ありませんが、たとえば、sent.2でそれを与えます-
文2=スコットランドという単語が含まれているが、文1の2番目に長い単語が含まれていない別の文。私のコードによると、この文は、スコットランドではなく、文1の2番目に長い単語を含む文である必要があります。
どうすればこれを解決できますか?私は可能な限りコードを最適化しようとしています。どんな助けでも大歓迎です。