In [9]:
import pandas as pd
import numpy as np
import re
import bottleneck as bn
import nltk
#nltk.download() to check 
from nltk.stem import PorterStemmer
from nltk.stem.wordnet import WordNetLemmatizer


file = open('sentences.txt')

In [2]:
text = []
uniqWords = set()
dictWords = {}
for line in file:
        line = re.compile('[^a-z]').split(line.lower())
        line = filter(None, line)
        uniqWords.update(line)            
        text.append(line)

print uniqWords


set(['displays', 'osx', 'selection', 'safari', 'just', 'developed', 'over', 'vermin', 'domestic', 'named', 'installed', 'symbols', 'through', 'human', 'world', 'disk', 'its', 'fifth', 'features', 'tamed', 'upgrade', 'lb', 'drive', 'to', 'won', 'deliberately', 'marks', 'has', 'predecessor', 'non', 'which', 'read', 'october', 'every', 'os', 'they', 'not', 'during', 'now', 'possess', 'intel', 'keyboards', 'bytes', 'unnecessary', 'patch', 'predators', 'small', 'output', 'entirely', 'where', 'ears', 'available', 'on', 'often', 'sequence', 'some', 'lion', 'frequency', 'are', 'year', 'download', 'terms', 'concern', 'error', 'for', 'pipes', 'since', 'factory', 'artificial', 'content', 'version', 'run', 'between', 'new', 'learned', 'three', 'piped', 'common', 'concatenate', 'be', 'weighing', 'genes', 'use', 'standard', 'release', 'diploid', 'members', 'x', 'based', 'safer', 'by', 'both', 'commands', 'installation', 'installs', 'of', 'needing', 'allows', 'according', 'july', 'later', 'mac', 's', 'streams', 'receives', 'successor', 'catenates', 'changes', 'or', 'felis', 'major', 'faint', 'useful', 'apple', 'app', 'community', 'one', 'running', 'unix', 'right', 'simply', 'linux', 'sounds', 'size', 'undergone', 'delete', 'from', 'enhancements', 'second', 'their', 'create', 'people', 'two', 't', 'redirection', 'however', 'cats', 'too', 'basic', 'permanently', 'type', 'dogs', 'store', 'more', 'files', 'releases', 'that', 'started', 'contains', 'releasing', 'tiger', 'released', 'part', 'hear', 'external', 'editions', 'off', 'mice', 'with', 'than', 'those', 'longer', 'count', 'made', 'animals', 'mavericks', 'versions', 'default', 'was', 'single', 'cat', 'will', 'can', 'were', 'wild', 'similar', 'interactive', 'and', 'mountain', 'computers', 'have', 'stdout', 'process', 'lines', 'is', 'received', 'moved', 'it', 'an', 'high', 'as', 'incremental', 'file', 'in', 'need', 'domesticated', 'any', 'domestication', 'if', 'binary', 'processors', 'no', 'rather', 'legibility', 'separate', 'firmware', 'when', 'mid', 'also', 'other', 'arguments', 'adjacent', 'online', 'instead', 'you', 'ancestor', 'offered', 'used', 'chromosomes', 'closest', 'information', 'may', 'symbol', 'leopard', 'update', 'most', 'wrong', 'connected', 'yosemite', 'such', 'comparison', 'recent', 'a', 'purchase', 'genus', 'kg', 'organisms', 'using', 'starting', 'clear', 'stdin', 'flow', 'roughly', 'so', 'switch', 'without', 'command', 'place', 'allow', 'time', 'redirected', 'the', 'typically', 'left'])

In [6]:
#Составьте список всех слов, встречающихся в предложениях. 
# Сопоставьте каждому слову индекс от нуля до (d - 1), где d — число различных слов в предложениях. 
# Для этого удобно воспользоваться структурой dict.
dictWords = dict(zip(uniqWords, range(len(uniqWords))))


{'osx': 1, 'selection': 2, 'safari': 3, 'just': 4, 'developed': 5, 'over': 6, 'vermin': 7, 'domestic': 8, 'major': 110, 'installed': 10, 'symbols': 11, 'through': 12, 'human': 13, 'world': 14, 'disk': 15, 'its': 16, 'fifth': 17, 'apple': 113, 'tamed': 19, 'upgrade': 20, 'lb': 21, 'computers': 179, 'to': 23, 'version': 70, 'deliberately': 25, 'marks': 26, 'has': 27, 'arguments': 210, 'predecessor': 28, 'non': 29, 'adjacent': 211, 'read': 31, 'made': 163, 'every': 33, 'they': 35, 'not': 36, 'during': 37, 'now': 38, 'people': 131, 'possess': 39, 'intel': 40, 'keyboards': 41, 'command': 246, 'bytes': 42, 'unnecessary': 43, 'patch': 44, 'common': 77, 'release': 84, 'output': 47, 'entirely': 48, 'where': 49, 'stdin': 240, 'ears': 50, 'concatenate': 78, 'right': 119, 'often': 53, 'wrong': 226, 'sequence': 54, 'some': 55, 'lion': 56, 'frequency': 57, 'displays': 0, 'year': 59, 'download': 60, 'terms': 61, 'firmware': 205, 'concern': 62, 'for': 64, 'pipes': 65, 'since': 66, 'factory': 67, 'artificial': 68, 'content': 69, 'won': 24, 'between': 72, 'kg': 235, 'new': 73, 'learned': 74, 'piped': 76, 'predators': 45, 'available': 51, 'be': 79, 'run': 71, 'genes': 81, 'undergone': 124, 'standard': 83, 'small': 46, 'were': 173, 'diploid': 85, 'members': 86, 'x': 87, 'based': 88, 'safer': 89, 'by': 90, 'on': 52, 'commands': 92, 'weighing': 80, 'installs': 94, 'of': 95, 'needing': 96, 'allows': 97, 'according': 98, 's': 102, 'streams': 103, 'receives': 104, 'successor': 105, 'catenates': 106, 'os': 34, 'or': 108, 'and': 177, 'named': 9, 'contains': 148, 'useful': 112, 'features': 18, 'app': 114, 'mice': 157, 'community': 115, 'one': 116, 'running': 117, 'unix': 118, 'simply': 120, 'linux': 121, 'sounds': 122, 'organisms': 236, 'size': 123, 'use': 82, 'delete': 125, 'from': 126, 'enhancements': 127, 'redirection': 134, 'create': 130, 'faint': 111, 'three': 75, 't': 133, 'their': 129, 'however': 135, 'cats': 136, 'too': 137, 'basic': 138, 'permanently': 139, 'type': 140, 'dogs': 141, 'store': 142, 'more': 143, 'files': 144, 'releases': 145, 'both': 91, 'started': 147, 'offered': 216, 'releasing': 149, 'tiger': 150, 'released': 151, 'part': 152, 'hear': 153, 'external': 154, 'editions': 155, 'installation': 93, 'july': 99, 'with': 158, 'than': 159, 'those': 160, 'count': 162, 'october': 32, 'animals': 164, 'mavericks': 165, 'versions': 166, 'default': 167, 'was': 168, 'typically': 252, 'second': 128, 'cat': 170, 'will': 171, 'information': 220, 'can': 172, 'error': 63, 'wild': 174, 'similar': 175, 'are': 58, 'felis': 109, 'interactive': 176, 'file': 192, 'stdout': 181, 'process': 182, 'flow': 241, 'is': 184, 'received': 185, 'moved': 186, 'it': 187, 'an': 188, 'high': 189, 'single': 169, 'incremental': 191, 'have': 180, 'in': 193, 'need': 194, 'domesticated': 195, 'any': 196, 'as': 190, 'if': 198, 'mountain': 178, 'processors': 200, 'no': 201, 'rather': 202, 'legibility': 203, 'separate': 204, 'that': 146, 'when': 206, 'mid': 207, 'also': 208, 'other': 209, 'domestication': 197, 'which': 30, 'online': 212, 'instead': 213, 'you': 214, 'ancestor': 215, 'used': 217, 'chromosomes': 218, 'closest': 219, 'binary': 199, 'may': 221, 'symbol': 222, 'leopard': 223, 'update': 224, 'most': 225, 'mac': 101, 'connected': 227, 'two': 132, 'yosemite': 228, 'such': 229, 'comparison': 230, 'recent': 231, 'a': 232, 'purchase': 233, 'genus': 234, 'off': 156, 'longer': 161, 'using': 237, 'changes': 107, 'clear': 239, 'later': 100, 'lines': 183, 'drive': 22, 'switch': 244, 'without': 245, 'so': 243, 'place': 247, 'allow': 248, 'time': 249, 'redirected': 250, 'the': 251, 'roughly': 242, 'starting': 238, 'left': 253}

In [10]:
# Создайте матрицу размера n * d, где n — число предложений. 
# Заполните ее: элемент с индексом (i, j) в этой матрице должен быть 
#     равен количеству вхождений j-го слова в i-е предложение. 
#     У вас должна получиться матрица размера 22 * 254.
n = len(text)
d = len(dictWords)
m = np.zeros((n,d))

for i in range(0,n):
    for word in text[i]:
        m[i][dictWords[word]] += 1

print m


[[ 0.  0.  0. ...,  1.  0.  0.]
 [ 0.  0.  0. ...,  0.  0.  0.]
 [ 0.  0.  0. ...,  1.  0.  0.]
 ..., 
 [ 0.  0.  0. ...,  2.  0.  0.]
 [ 0.  0.  0. ...,  1.  0.  0.]
 [ 0.  0.  0. ...,  1.  0.  0.]]

In [15]:
# Найдите косинусное расстояние от предложения в самой первой строке 
# (In comparison to dogs, cats have not undergone...) до всех остальных с помощью 
# функции scipy.spatial.distance.cosine. Какие номера у двух предложений, ближайших 
# к нему по этому расстоянию (строки нумеруются с нуля)? Эти два числа и будут ответами на задание.
from scipy.spatial import distance
distances = list()
for i in range(1,n):
    distances.append(distance.cosine(m[0],m[i]))
    
print distances


[0.95275444087384664, 0.86447381456421235, 0.89517151632780823, 0.77708871496985887, 0.94023856953328033, 0.7327387580875756, 0.92587506833388988, 0.88427248752843102, 0.90550888174769317, 0.83281653622739416, 0.88047713906656067, 0.83964325485254543, 0.87035925528956715, 0.87401184233025764, 0.94427217874246472, 0.84063618542208085, 0.95664450152379399, 0.94427217874246472, 0.88854435748492944, 0.84275727449171223, 0.82503644694405864]

In [29]:
result = np.argpartition(distances,2)[0:2] + 1
print result
print distances[result[0]], distances[result[1]]


[6 4]
0.925875068334 0.940238569533

In [35]:
a = bn.partsort(np.asarray(distances), 2)[:2]
b = bn.argpartsort(np.asarray(distances), 2)[:2]+1

print a,b


[ 0.73273876  0.77708871] [6 4]

In [2]:
print lemmatizer.lemmatize('gathering', 'v')
print lemmatizer.lemmatize('gathering', 'n')


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-2-f1d0c9c21efc> in <module>()
----> 1 print lemmatizer.lemmatize('gathering', 'v')
      2 print lemmatizer.lemmatize('gathering', 'n')

NameError: name 'lemmatizer' is not defined

In [10]:
lemmatizer = WordNetLemmatizer()
stemmer = PorterStemmer()

text = []
uniqWords1 = set()
uniqWords2 = set()
dictWords = {}
for line in file:
        line = re.compile('[^a-z]').split(line.lower())
        line = filter(None, line)
      
        uniqWords1.update(line)            

        line = map(lambda word : stemmer.stem(lemmatizer.lemmatize(word)), line)
      
        uniqWords2.update(line)            
        text.append(line)

In [11]:
print len(uniqWords1), len(uniqWords2)


254 230

In [3]:
file.close()