Created
January 17, 2012 15:38
-
-
Save AlexDel/1627107 to your computer and use it in GitHub Desktop.
NLTk Ex 2.24.c Алгоритм порождения случайного связного текста из гибридного жанра
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.brown.words(categories = ['religion','science_fiction']) | |
bigrams = nltk.bigrams(text) | |
cfd = nltk.ConditionalFreqDist(bigrams) | |
generate_model(cfd, 'but') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment