- •Мета робота
- •Короткі теоретичні відомості
- •1. Поняття функції та модуля.
- •1.1. Створення скриптів
- •2. Генерація випадкового тексту за допомогою біграмів
- •3. Лексичні ресурси nltk. Корпуси слів
- •3.1. Корпус words
- •3.2. Корпус стоп-слів
- •3.3. Корпус імен
- •4. Словники
- •4.1. Словник із позначенням вимови
- •Виконати самостійно
- •4.2. Порівняльні (компаративні) словники
- •5. WordNet – лексична база даних англійської мови
- •5.1. Значення і синоніми
- •5.2. Ієрархія в WordNet
- •5.3. Лексичні зв’язки в WordNet.
- •5.4. Оцінка подібності в WordNet
- •Додаток а
- •Порядок виконання роботи
- •Література
- •Інтернет посилання
- •Методичні вказівки
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
