Skip to content

Instantly share code, notes, and snippets.

@AlexDel
AlexDel / gist:1588878
Created January 10, 2012 12:45
Genre diversity score. Считаем лексическую насыщенность в корпусе Брауна и выводим данные. NLTK Упр 2.16
import nltk
from __future__ import division
for genre in nltk.corpus.brown.categories():
words = nltk.corpus.brown.words(categories = genre)
print genre +' - ' + str(round((len(set(words))/len(words)),6)*100) + '%'
@AlexDel
AlexDel / gist:1589239
Created January 10, 2012 14:03
NLTK. Ex 2.17 Write a function that finds the 50 most frequently occurring words of a text that are not stopwords.
def freq_non_stopwords(text):
stopwords = nltk.corpus.stopwords.words('english')
clean_list = [w for w in text if w.lower() not in stopwords] #убираем частотные слова
freqdist = nltk.probability.FreqDist(clean_list)
return freqdist.keys()[:50] #возвращаем 50 первых нечастотных слов
@AlexDel
AlexDel / gist:1589515
Created January 10, 2012 15:10
NLTK. Ex 2.18 Write a program to print the 50 most frequent bigrams (pairs of adjacent words) of a text, omitting bigrams that contain stopwords.
def top_bigrams(text):
fdist = nltk.probability.FreqDist(nltk.bigrams(text)) #формируем список кортежей биграмм
stopwords = nltk.corpus.stopwords.words('english') #формируем стоплист
top_list = [(x,y) for x,y in fdist.keys() if x.isalpha() and y.isalpha() and x not in stopwords and y not in stopwords] #показываем только если элементы кортежа - слова и невходят в стоплист
return top_list
@AlexDel
AlexDel / gist:1593588
Created January 11, 2012 07:39
NLTK EX 2.20 Write a function word_freq() that takes a word and the name of a section of the Brown Corpus as arguments, and computes the frequency of the word in that section of the corpus.
def word_freq(word, section):
freq = nltk.probability.FreqDist(nltk.corpus.brown.words(categories = section))
word_frequency = freq[word]
return word_frequency
@AlexDel
AlexDel / gist:1593818
Created January 11, 2012 09:05
NLTK Ex 2.21 Write a program to guess the number of syllables contained in a text, making use of the CMU Pronouncing Dictionary
d = nltk.corpus.cmudict.dict() #получаем объект в виде словаря для удобного доступа
def count_syllables(text): #вводим текст как список слов
syll_text = [] #исходный массив где будут копиться слоги
for word in text:
syll_text.extend(d[word][0]) #к исходному массиву добавляем первый элемент (в случае нескольких произношений)с помощью метода extend
return len(syll_text)# ву-а-ля
@AlexDel
AlexDel / gist:1616022
Created January 15, 2012 14:32
NLTk Ex 2.23.a Строим график по Закону Ципфа для корпуса Брауна
import nltk
import matplotlib.pyplot as plt
words = nltk.corpus.brown.words() #выбираем все слова из корпуса
def zipf_law(words):
freq_dist = nltk.FreqDist(words)#считаем кол-во вхождений
xaxis = []
yaxis = []
@AlexDel
AlexDel / gist:1616220
Created January 15, 2012 15:46
NLTk Ex 2.23.b Строим график по Закону Ципфа для случайной последовательности
import nltk
import matplotlib.pyplot as plt
import random
random_string = '' #инициализируем переменную
#превращаем ее в строку случайных символов
while len(random_string) < 9964284: #кол-во букв в брауновском корпусе
random_string += random.choice("abcdefgklmnopqrstuvwxyz ")
@AlexDel
AlexDel / gist:1627060
Created January 17, 2012 15:27
NLTk Ex 2.24.a Алгоритм порождения случайного связного текста
#Суть алгоритма такова: из текста мы делаем множество биграмм - кортежей вида (x,y).
#Затем мы берем начальное слово и выбираем другое случайное, идущее с ним в биграмме.
#К этому случайному добавляем очередное случайное из биграммы и т.л.
#Случайность выбора помогает не создавать "петлей"
import nltk
import random
def generate_model(cfdist, word, num=15):
for i in range(num):
@AlexDel
AlexDel / gist:1627107
Created January 17, 2012 15:38
NLTk Ex 2.24.c Алгоритм порождения случайного связного текста из гибридного жанра
#Суть алгоритма такова: из текста мы делаем множество биграмм - кортежей вида (x,y).
#Затем мы берем начальное слово и выбираем другое случайное, идущее с ним в биграмме.
#К этому случайному добавляем очередное случайное из биграммы и т.л.
#Случайность выбора помогает не создавать "петлей"
#Слова берутся из корпуса смешанного из двух жанров
import nltk
import random
def generate_model(cfdist, word, num=15):
<? function video_preview()
{
$this->load->model('text/text_model');
$params = array(
'node_tree_id' => 22,#заменить на требуемое
'from_subfolders' => 1,
'full_text' => 1,
'limit' => 4
);