Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
2011-kl-lab5.doc
Скачиваний:
7
Добавлен:
12.11.2019
Размер:
1.21 Mб
Скачать

2. Генерація випадкового тексту за допомогою біграмів

Умовний частотний розподіл можна використати для побудови таблиці біграмів (пар слів). Функція NLTK bigrams() , як аргумент бере список слів і повертає список послідовних пар слів.

>>> sent = ['In', 'the', 'beginning', 'God', 'created', 'the', 'heaven', 'and', 'the', 'earth', '.']

>>> nltk.bigrams(sent)

[('In', 'the'), ('the', 'beginning'), ('beginning', 'God'), ('God', 'created'), ('created', 'the'), ('the', 'heaven'), ('heaven', 'and'), ('and', 'the'), ('the', 'earth'), ('earth', '.')]

В наступному прикладі кожне слово розглядається, як умова і для кожного з них будується частотний розподіл по словам, які слідують після нього.

>>> import nltk

>>> from nltk.corpus import genesis

>>> text = nltk.corpus.genesis.words('english-kjv.txt')

>>> bigrams = nltk.bigrams(text)

>>> cfd = nltk.ConditionalFreqDist(bigrams)

>>> print cfd['living']

<FreqDist: 'creature': 7, 'thing': 4, 'substance': 2, ',': 1, '.': 1, 'soul': 1>

Для перевірки вірності отриманого результату побудуємо конкорданс для слова living

>>> len(text)

44764

>>> text_concordance = nltk.Text(nltk.corpus.genesis.words('english-kjv.txt'))

>>> text_concordance.concordance("living")

Building index...

Displaying 16 of 16 matches:

od created great whales , and every living creature that moveth , which the wa

aid , Let the earth bring forth the living creature after his kind , cattle ,

he fowl of the air , and over every living thing that moveth upon the earth .

e breath of life ; and man became a living soul . And the LORD God planted a g

th and whatsoever Adam called every living creature , that was the name thereo

; because she was the mother of all living . Unto Adam also and to his wife di

ns ' wives with thee . And of every living thing of all flesh , two of every s

y days and forty nights ; and every living substance that I have made will I d

in the dry land , died . And every living substance was destroyed which was u

And God remembered Noah , and every living thing , and all the cattle that was

thee . Bring forth with thee every living thing that is with thee , of all fl

I again smite any more every thing living , as I have done . While the earth

our seed after you ; And with every living creature that is with you , of the

I make between me and you and every living creature that is with you , for per

ich is between me and you and every living creature of all flesh ; and the wat

ting covenant between God and every living creature of all flesh that is upon

Функція generate_model() містить простий цикл для генерації тексту. Коли ця функція викликається, то одним з її аргументів є слово – початковий контекст (у прикладі 'living') .

В циклі поточне значення змінної word виводиться на екран і її значення замінюється на слово, яке найчастіше є наступним словом (max()) . На наступному кроці циклу вже це слово буде наступним контекстом. Запропонований підхід генерації тексту швидко приводить до зациклювання, якого можна уникнути якщо вибирати наступні слова випадковим чином.

def generate_model(cfdist, word, num=15):

for i in range(num):

print word,

word = cfdist[word].max()

>>> generate_model(cfd, 'living')

living creature that he said , and the land of the land of the land

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]