2014-09-11 14:57:08 +00:00
|
|
|
from libc.stdlib cimport calloc, free, realloc
|
|
|
|
|
|
|
|
from spacy.word cimport Lexeme
|
|
|
|
from spacy.lexeme cimport lexeme_check_flag
|
|
|
|
from spacy.lexeme cimport lexeme_string_view
|
|
|
|
|
|
|
|
|
2014-09-10 16:11:13 +00:00
|
|
|
cdef class Tokens:
|
|
|
|
"""A sequence of references to Lexeme objects.
|
|
|
|
|
|
|
|
The Tokens class provides fast and memory-efficient access to lexical features,
|
|
|
|
and can efficiently export the data to a numpy array. Specific languages
|
|
|
|
create their own Tokens subclasses, to provide more convenient access to
|
|
|
|
language-specific features.
|
|
|
|
|
|
|
|
>>> from spacy.en import EN
|
|
|
|
>>> tokens = EN.tokenize('An example sentence.')
|
|
|
|
>>> tokens.string(0)
|
|
|
|
'An'
|
|
|
|
>>> tokens.prob(0) > tokens.prob(1)
|
|
|
|
True
|
|
|
|
>>> tokens.can_noun(0)
|
|
|
|
False
|
|
|
|
>>> tokens.can_noun(1)
|
|
|
|
True
|
|
|
|
"""
|
2014-09-11 22:18:31 +00:00
|
|
|
def __cinit__(self, string_length=0):
|
|
|
|
size = int(string_length / 3) if string_length >= 3 else 1
|
2014-09-11 14:57:08 +00:00
|
|
|
self.lexemes = <LexemeC**>calloc(size, sizeof(LexemeC*))
|
|
|
|
self.size = size
|
|
|
|
self.length = 0
|
|
|
|
|
2014-09-11 22:18:31 +00:00
|
|
|
def __dealloc__(self):
|
|
|
|
free(self.lexemes)
|
|
|
|
|
2014-09-11 19:37:32 +00:00
|
|
|
def __getitem__(self, i):
|
|
|
|
if i >= self.length:
|
|
|
|
raise IndexError
|
|
|
|
return Lexeme(<size_t>self.lexemes[i])
|
|
|
|
|
|
|
|
def __len__(self):
|
|
|
|
return self.length
|
|
|
|
|
2014-09-11 14:57:08 +00:00
|
|
|
def append(self, Lexeme lexeme):
|
|
|
|
self.push_back(lexeme._c)
|
|
|
|
|
|
|
|
cdef push_back(self, LexemeC* lexeme):
|
|
|
|
if (self.size + 1) == self.length:
|
|
|
|
self.size *= 2
|
|
|
|
self.lexemes = <LexemeC**>realloc(self.lexemes, self.size * sizeof(LexemeC*))
|
|
|
|
self.lexemes[self.length] = lexeme
|
|
|
|
self.length += 1
|
2014-09-10 16:11:13 +00:00
|
|
|
|
|
|
|
cpdef unicode string(self, size_t i):
|
2014-09-11 14:57:08 +00:00
|
|
|
cdef bytes byte_string = self.lexemes[i].string
|
|
|
|
return byte_string.decode('utf8')
|
2014-09-10 16:11:13 +00:00
|
|
|
|
|
|
|
cpdef double prob(self, size_t i):
|
|
|
|
return self.lexemes[i].prob
|
|
|
|
|
|
|
|
cpdef size_t cluster(self, size_t i):
|
|
|
|
return self.lexemes[i].cluster
|
|
|
|
|
|
|
|
cpdef bint check_flag(self, size_t i, size_t flag_id):
|
2014-09-11 14:57:08 +00:00
|
|
|
return lexeme_check_flag(self.lexemes[i], flag_id)
|
2014-09-10 16:11:13 +00:00
|
|
|
|
|
|
|
cpdef unicode string_view(self, size_t i, size_t view_id):
|
2014-09-11 14:57:08 +00:00
|
|
|
return lexeme_string_view(self.lexemes[i], view_id)
|