我正在研究一个随机文本生成器 - 没有使用马尔可夫链 - 目前它的工作没有太多问题 - 实际上按照我的标准生成了大量的随机句子但是我想让它更准确地防止许多句子尽可能重复 - 。首先,这是我的代码流程:
输入一个句子作为输入 - 这称为触发字符串,分配给变量 -
获取触发器字符串中最长的单词
在所有Project Gutenberg数据库中搜索包含此单词的句子 - 无大写小写 -
返回包含我在第3步中提到的单词的最长句子
将步骤1和步骤4中的句子一起附加
将步骤4中的句子指定为新的“触发器”句子并重复该过程。请注意,我必须在第二句中获得最长的单词并继续这样,依此类推 -
这是我的代码:
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行开始到结束 - 但算法仍然可以在出现的句子中选择相同的最长单词,而不是寻找第二长单词。
例如:
Trigger string =“苏格兰是一个不错的地方。”
句子1 = - 这是一个随机的句子,里面有苏格兰词 -
现在,这就是我的代码中有时会出现问题的地方 - 无论是在句子2还是942或者zillion或者其他任何内容中都会出现问题,但是我在发送过程中给出了它,例如,为了这个原因 -
句子2 =另一句话中包含苏格兰语,但不是句子1中第二长的单词。根据我的代码,这句话应该是一句话,其中包含句子1中第二长的单词,而不是苏格兰!
我该如何解决这个问题?我正在尝试尽可能地优化代码,欢迎任何帮助。
答案 0 :(得分:0)
根本没有随机的算法。它应该始终是确定性的。
我不太清楚你想在这做什么。如果要生成随机单词,只需使用字典和随机模块。如果你想从Gutenberg项目中获取随机句子,可以使用随机模块选择一项工作,然后从该工作中选择一个句子。