我正在尝试通过 python 的正则表达式和 NLTK 处理各种文本-位于http://www.nltk.org/book-。我正在尝试创建一个随机文本生成器,但遇到了一个小问题。首先,这是我的代码流程:
输入一个句子作为输入-这称为触发字符串,分配给一个变量-
获取触发字符串中最长的单词
在所有 Project Gutenberg 数据库中搜索包含此单词的句子 - 不管大写小写 -
返回包含我在步骤 3 中谈到的单词的最长句子
将步骤 1 和步骤 4 中的句子附加在一起
将步骤 4 中的句子指定为新的“触发”句子并重复该过程。请注意,我必须在第二句中找到最长的单词并继续这样,依此类推-
到目前为止,我只能这样做一次。当我试图让这个继续下去时,程序只继续打印我的搜索产生的第一句话。它实际上应该在这个新句子中寻找最长的单词并继续应用我上面描述的代码流。
下面是我的代码以及示例输入/输出:
样本输入
“密码之王”
样本输出
“代码的领主挪威本人,数字可怕,在最不忠的叛徒考多领主的协助下,开始了一场小冲突,直到贝罗纳的新郎,在校对中,用自我比较来对抗他,点对点,叛逆的Arme'gainst Arme,抑制了他的狂妄自大的精神:最后,胜利落在了vs上
现在这实际上应该采用以“挪威自己......”开头的句子并寻找其中最长的单词并执行上述步骤等等,但事实并非如此。有什么建议么?谢谢。
import nltk
from nltk.corpus import gutenberg
triggerSentence = raw_input("Please enter the trigger sentence: ")#get input str
split_str = triggerSentence.split()#split the sentence into words
longestLength = 0
longestString = ""
montyPython = 1
while montyPython:
#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)
listOfSents = gutenberg.sents() #all sentences of gutenberg are assigned -list of list format-
listOfWords = gutenberg.words()# all words in gutenberg books -list format-
# I tip my hat to Mr.Alex Martelli for this part, which helps me find the longest sentence
lt = longestString.lower() #this line tells you whether word list has the longest word in a case-insensitive way.
longestSentence = max((listOfWords for listOfWords in listOfSents if any(lt == word.lower() for word in listOfWords)), key = len)
#get longest sentence -list format with every word of sentence being an actual element-
longestSent=[longestSentence]
for word in longestSent:#convert the list longestSentence to an actual string
sstr = " ".join(word)
print triggerSentence + " "+ sstr
triggerSentence = sstr