Created
January 17, 2012 15:27
-
-
Save AlexDel/1627060 to your computer and use it in GitHub Desktop.
NLTk Ex 2.24.a Алгоритм порождения случайного связного текста
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Суть алгоритма такова: из текста мы делаем множество биграмм - кортежей вида (x,y). | |
#Затем мы берем начальное слово и выбираем другое случайное, идущее с ним в биграмме. | |
#К этому случайному добавляем очередное случайное из биграммы и т.л. | |
#Случайность выбора помогает не создавать "петлей" | |
import nltk | |
import random | |
def generate_model(cfdist, word, num=15): | |
for i in range(num): | |
print word, | |
word = random.choice(list(cfdist[word])) | |
text = nltk.corpus.genesis.words('english-kjv.txt') #берем текст | |
bigrams = nltk.bigrams(text) #разбиваем на биграммы | |
cfd = nltk.ConditionalFreqDist(bigrams) #в принципе можно обойтись без этого | |
generate_model(cfd, 'living') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment