INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Predict the median lifetimes for the individuals. If the survival curve of an individual does not cross 0.5, then the result is infinity. Parameters ---------- X: numpy array or DataFrame a (n,d) covariate numpy array or DataFrame. If a DataFrame, columns can be ...
def predict_median(self, X, ancillary_X=None): """ Predict the median lifetimes for the individuals. If the survival curve of an individual does not cross 0.5, then the result is infinity. Parameters ---------- X: numpy array or DataFrame a (n,d) covariate nu...
The concordance score (also known as the c-index) of the fit. The c-index is a generalization of the ROC AUC to survival data, including censorships. For this purpose, the ``score_`` is a measure of the predictive accuracy of the fitted model onto the training dataset.
def score_(self): """ The concordance score (also known as the c-index) of the fit. The c-index is a generalization of the ROC AUC to survival data, including censorships. For this purpose, the ``score_`` is a measure of the predictive accuracy of the fitted model onto the trai...
Produces a visual representation of the coefficients, including their standard errors and magnitudes. Parameters ---------- columns : list, optional specify a subset of the columns to plot errorbar_kwargs: pass in additional plotting commands to matplotlib errorb...
def plot(self, columns=None, parameter=None, **errorbar_kwargs): """ Produces a visual representation of the coefficients, including their standard errors and magnitudes. Parameters ---------- columns : list, optional specify a subset of the columns to plot e...
Produces a visual representation comparing the baseline survival curve of the model versus what happens when a covariate(s) is varied over values in a group. This is useful to compare subjects' survival as we vary covariate(s), all else being held equal. The baseline survival curve is equal to t...
def plot_covariate_groups(self, covariates, values, plot_baseline=True, **kwargs): """ Produces a visual representation comparing the baseline survival curve of the model versus what happens when a covariate(s) is varied over values in a group. This is useful to compare subjects' surviva...
Returns the median lifetimes for the individuals, by default. If the survival curve of an individual does not cross ``p``, then the result is infinity. http://stats.stackexchange.com/questions/102986/percentile-loss-functions Parameters ---------- X: numpy array or DataFrame ...
def predict_percentile(self, X, ancillary_X=None, p=0.5): """ Returns the median lifetimes for the individuals, by default. If the survival curve of an individual does not cross ``p``, then the result is infinity. http://stats.stackexchange.com/questions/102986/percentile-loss-functions ...
Predict the expectation of lifetimes, :math:`E[T | x]`. Parameters ---------- X: numpy array or DataFrame a (n,d) covariate numpy array or DataFrame. If a DataFrame, columns can be in any order. If a numpy array, columns must be in the same order as the train...
def predict_expectation(self, X, ancillary_X=None): """ Predict the expectation of lifetimes, :math:`E[T | x]`. Parameters ---------- X: numpy array or DataFrame a (n,d) covariate numpy array or DataFrame. If a DataFrame, columns can be in any order. If a...
Return the cumulative hazard rate of subjects in X at time points. Parameters ---------- X: numpy array or DataFrame a (n,d) covariate numpy array or DataFrame. If a DataFrame, columns can be in any order. If a numpy array, columns must be in the same order a...
def predict_cumulative_hazard(self, X, times=None, ancillary_X=None): """ Return the cumulative hazard rate of subjects in X at time points. Parameters ---------- X: numpy array or DataFrame a (n,d) covariate numpy array or DataFrame. If a DataFrame, columns ...
Parameters ----------- durations: an array, or pd.Series, of length n duration subject was observed for timeline: iterable return the best estimate at the values in timelines (positively increasing) event_observed: an array, or pd.Series, of length n Tru...
def fit( self, durations, event_observed=None, timeline=None, entry=None, label="NA_estimate", alpha=None, ci_labels=None, weights=None, ): # pylint: disable=too-many-arguments """ Parameters ----------- duratio...
Parameters ----------- bandwidth: float the bandwith used in the Epanechnikov kernel. Returns ------- DataFrame: a DataFrame of the smoothed hazard
def smoothed_hazard_(self, bandwidth): """ Parameters ----------- bandwidth: float the bandwith used in the Epanechnikov kernel. Returns ------- DataFrame: a DataFrame of the smoothed hazard """ timeline = self.timeline ...
Parameters ---------- bandwidth: float the bandwidth to use in the Epanechnikov kernel. > 0 hazard_: numpy array a computed (n,) numpy array of estimated hazard rates. If none, uses ``smoothed_hazard_``
def smoothed_hazard_confidence_intervals_(self, bandwidth, hazard_=None): """ Parameters ---------- bandwidth: float the bandwidth to use in the Epanechnikov kernel. > 0 hazard_: numpy array a computed (n,) numpy array of estimated hazard rates. If non...
Convert the np.ndarray `values` into a complete balanced tree. Assumes `values` is sorted ascending. Returns a list `t` of the same length in which t[i] > t[2i+1] and t[i] < t[2i+2] for all i.
def _treeify(values): """Convert the np.ndarray `values` into a complete balanced tree. Assumes `values` is sorted ascending. Returns a list `t` of the same length in which t[i] > t[2i+1] and t[i] < t[2i+2] for all i.""" if len(values) == 1: # this case causes problems later ...
Insert an occurrence of `value` into the btree.
def insert(self, value): """Insert an occurrence of `value` into the btree.""" i = 0 n = len(self._tree) while i < n: cur = self._tree[i] self._counts[i] += 1 if value < cur: i = 2 * i + 1 elif value > cur: i...
Returns the rank and count of the value in the btree.
def rank(self, value): """Returns the rank and count of the value in the btree.""" i = 0 n = len(self._tree) rank = 0 count = 0 while i < n: cur = self._tree[i] if value < cur: i = 2 * i + 1 continue elif...
Produces a quantile-quantile plot of the empirical CDF against the fitted parametric CDF. Large deviances away from the line y=x can invalidate a model (though we expect some natural deviance in the tails). Parameters ----------- model: obj A fitted lifelines univariate parametric model, li...
def qq_plot(model, **plot_kwargs): """ Produces a quantile-quantile plot of the empirical CDF against the fitted parametric CDF. Large deviances away from the line y=x can invalidate a model (though we expect some natural deviance in the tails). Parameters ----------- model: obj A f...
Remove spines of axis. Parameters: ax: axes to operate on sides: list of sides: top, left, bottom, right Examples: removespines(ax, ['top']) removespines(ax, ['top', 'bottom', 'right', 'left'])
def remove_spines(ax, sides): """ Remove spines of axis. Parameters: ax: axes to operate on sides: list of sides: top, left, bottom, right Examples: removespines(ax, ['top']) removespines(ax, ['top', 'bottom', 'right', 'left']) """ for side in sides: ax.spines[side]...
Move the entire spine relative to the figure. Parameters: ax: axes to operate on sides: list of sides to move. Sides: top, left, bottom, right dists: list of float distances to move. Should match sides in length. Example: move_spines(ax, sides=['left', 'bottom'], dists=[-0.02, 0.1])
def move_spines(ax, sides, dists): """ Move the entire spine relative to the figure. Parameters: ax: axes to operate on sides: list of sides to move. Sides: top, left, bottom, right dists: list of float distances to move. Should match sides in length. Example: move_spines(ax, sid...
Remove ticks from axis. Parameters: ax: axes to work on x: if True, remove xticks. Default False. y: if True, remove yticks. Default False. Examples: removeticks(ax, x=True) removeticks(ax, x=True, y=True)
def remove_ticks(ax, x=False, y=False): """ Remove ticks from axis. Parameters: ax: axes to work on x: if True, remove xticks. Default False. y: if True, remove yticks. Default False. Examples: removeticks(ax, x=True) removeticks(ax, x=True, y=True) """ if x: ...
Add counts showing how many individuals were at risk at each time point in survival/hazard plots. Parameters ---------- fitters: One or several fitters, for example KaplanMeierFitter, NelsonAalenFitter, etc... Returns -------- ax: The axes which was used. Examples -...
def add_at_risk_counts(*fitters, **kwargs): """ Add counts showing how many individuals were at risk at each time point in survival/hazard plots. Parameters ---------- fitters: One or several fitters, for example KaplanMeierFitter, NelsonAalenFitter, etc... Returns -------...
Returns a lifetime plot, see examples: https://lifelines.readthedocs.io/en/latest/Survival%20Analysis%20intro.html#Censoring Parameters ----------- durations: (n,) numpy array or pd.Series duration subject was observed for. event_observed: (n,) numpy array or pd.Series array of booleans: Tr...
def plot_lifetimes( durations, event_observed=None, entry=None, left_truncated=False, sort_by_duration=True, event_observed_color="#A60628", event_censored_color="#348ABD", **kwargs ): """ Returns a lifetime plot, see examples: https://lifelines.readthedocs.io/en/latest/Survival%...
Specifies a plot of the log(-log(SV)) versus log(time) where SV is the estimated survival function.
def plot_loglogs(cls, loc=None, iloc=None, show_censors=False, censor_styles=None, **kwargs): """ Specifies a plot of the log(-log(SV)) versus log(time) where SV is the estimated survival function. """ def loglog(s): return np.log(-np.log(s)) if (loc is not None) and (iloc is not None): ...
Plots a pretty figure of {0}.{1} Matplotlib plot arguments can be passed in inside the kwargs, plus Parameters ----------- show_censors: bool place markers at censorship events. Default: False censor_styles: bool If show_censors, this dictionary will be passed into the plot call. ...
def _plot_estimate( cls, estimate=None, confidence_intervals=None, loc=None, iloc=None, show_censors=False, censor_styles=None, ci_legend=False, ci_force_lines=False, ci_alpha=0.25, ci_show=True, at_risk_counts=False, **kwargs ): """ Plots a pretty figure of ...
translate a word document type of file and save the result as document and keep the exactly same file format. :param filename: word doc file :param destination='zh-CN': :param mix=True: if True, will have original language and target language into the same doc. paragraphs by paragraphs.
def translate_doc(filename, destination='zh-CN', mix=True): """ translate a word document type of file and save the result as document and keep the exactly same file format. :param filename: word doc file :param destination='zh-CN': :param mix=True: if True, will have original languag...
Translate text from source language to destination language :param text: The source text(s) to be translated. Batch translation is supported via sequence input. :type text: UTF-8 :class:`str`; :class:`unicode`; string sequence (list, tuple, iterator, generator) :param dest: The language to tra...
def translate(self, text, dest='en', src='auto'): """Translate text from source language to destination language :param text: The source text(s) to be translated. Batch translation is supported via sequence input. :type text: UTF-8 :class:`str`; :class:`unicode`; string sequence (list, tuple, i...
Detect language of the input text :param text: The source text(s) whose language you want to identify. Batch detection is supported via sequence input. :type text: UTF-8 :class:`str`; :class:`unicode`; string sequence (list, tuple, iterator, generator) :rtype: Detected ...
def detect(self, text): """Detect language of the input text :param text: The source text(s) whose language you want to identify. Batch detection is supported via sequence input. :type text: UTF-8 :class:`str`; :class:`unicode`; string sequence (list, tuple, iterator, gener...
update tkk
def _update(self): """update tkk """ # we don't need to update the base TKK value when it is still valid now = math.floor(int(time.time() * 1000) / 3600000.0) if self.tkk and int(self.tkk.split('.')[0]) == now: return r = self.session.get(self.host) ...
Wheel filenames contain the python version and the python ABI version for the wheel. https://www.python.org/dev/peps/pep-0427/#file-name-convention Since we're distributing a rust binary this doesn't matter for us ...
def make_wheel_filename_generic(wheel): """ Wheel filenames contain the python version and the python ABI version for the wheel. https://www.python.org/dev/peps/pep-0427/#file-name-convention Since we're distributing a rust binary this doesn't matter for us ... """ name, version, python, abi, platform =...
Only most frequent k words to be included in the embeddings.
def most_frequent(self, k, inplace=False): """Only most frequent k words to be included in the embeddings.""" vocabulary = self.vocabulary.most_frequent(k) vectors = np.asarray([self[w] for w in vocabulary]) if inplace: self.vocabulary = vocabulary self.vectors = vectors return self ...
Normalize embeddings matrix row-wise. Args: ord: normalization order. Possible values {1, 2, 'inf', '-inf'}
def normalize_words(self, ord=2, inplace=False): """Normalize embeddings matrix row-wise. Args: ord: normalization order. Possible values {1, 2, 'inf', '-inf'} """ if ord == 2: ord = None # numpy uses this flag to indicate l2. vectors = self.vectors.T / np.linalg.norm(self.vectors, ord,...
Return the nearest k words to the given `word`. Args: word (string): single word. top_k (integer): decides how many neighbors to report. Returns: A list of words sorted by the distances. The closest is the first. Note: L2 metric is used to calculate distances.
def nearest_neighbors(self, word, top_k=10): """Return the nearest k words to the given `word`. Args: word (string): single word. top_k (integer): decides how many neighbors to report. Returns: A list of words sorted by the distances. The closest is the first. Note: L2 metric ...
Calculate eucledean pairwise distances between `word` and `words`. Args: word (string): single word. words (list): list of strings. Returns: numpy array of the distances. Note: L2 metric is used to calculate distances.
def distances(self, word, words): """Calculate eucledean pairwise distances between `word` and `words`. Args: word (string): single word. words (list): list of strings. Returns: numpy array of the distances. Note: L2 metric is used to calculate distances. """ point = ...
Load the input-hidden weight matrix from the original C word2vec-tool format. Note that the information stored in the file is incomplete (the binary tree is missing), so while you can query for word similarity etc., you cannot continue training with a model loaded this way. `binary` is a boolean indic...
def from_word2vec(fname, fvocab=None, binary=False): """ Load the input-hidden weight matrix from the original C word2vec-tool format. Note that the information stored in the file is incomplete (the binary tree is missing), so while you can query for word similarity etc., you cannot continue training ...
Load an embedding dump generated by `save`
def load(fname): """Load an embedding dump generated by `save`""" content = _open(fname).read() if PY2: state = pickle.loads(content) else: state = pickle.loads(content, encoding='latin1') voc, vec = state if len(voc) == 2: words, counts = voc word_count = dict(zip(words...
Save a pickled version of the embedding into `fname`.
def save(self, fname): """Save a pickled version of the embedding into `fname`.""" vec = self.vectors voc = self.vocabulary.getstate() state = (voc, vec) with open(fname, 'wb') as f: pickle.dump(state, f, protocol=pickle.HIGHEST_PROTOCOL)
Extract the contents of the zip file ``filename`` into the directory ``root``.
def unzip(filename, root, verbose=True): """ Extract the contents of the zip file ``filename`` into the directory ``root``. """ for message in _unzip_iter(filename, root, verbose): if isinstance(message, ErrorMessage): raise Exception(message)
Create a new data.xml index file, by combining the xml description files for various packages and collections. ``root`` should be the path to a directory containing the package xml and zip files; and the collection xml files. The ``root`` directory is expected to have the following subdirectories:: root/...
def build_index(root, base_url): """ Create a new data.xml index file, by combining the xml description files for various packages and collections. ``root`` should be the path to a directory containing the package xml and zip files; and the collection xml files. The ``root`` directory is expected to have ...
Helper for ``build_index()``: Given an XML ``ElementTree``, modify it (and its descendents) ``text`` and ``tail`` attributes to generate an indented tree, where each nested element is indented by 2 spaces with respect to its parent.
def _indent_xml(xml, prefix=''): """ Helper for ``build_index()``: Given an XML ``ElementTree``, modify it (and its descendents) ``text`` and ``tail`` attributes to generate an indented tree, where each nested element is indented by 2 spaces with respect to its parent. """ if len(xml) > 0: xml.text = ...
Helper for ``build_index()``: Perform some checks to make sure that the given package is consistent.
def _check_package(pkg_xml, zipfilename, zf): """ Helper for ``build_index()``: Perform some checks to make sure that the given package is consistent. """ # The filename must patch the id given in the XML file. uid = os.path.splitext(os.path.split(zipfilename)[1])[0] if pkg_xml.get('id') != uid: raise...
Helper for ``build_index()``: Calculate the subversion revision number for a given file (by using ``subprocess`` to run ``svn``).
def _svn_revision(filename): """ Helper for ``build_index()``: Calculate the subversion revision number for a given file (by using ``subprocess`` to run ``svn``). """ p = subprocess.Popen(['svn', 'status', '-v', filename], stdout=subprocess.PIPE, stderr=subprocess.PIPE) (stdout, st...
Helper for ``build_index()``: Yield a list of ElementTree.Element objects, each holding the xml for a single package collection.
def _find_collections(root): """ Helper for ``build_index()``: Yield a list of ElementTree.Element objects, each holding the xml for a single package collection. """ packages = [] for dirname, subdirs, files in os.walk(root): for filename in files: if filename.endswith('.xml'): xmlfile = o...
Helper for ``build_index()``: Yield a list of tuples ``(pkg_xml, zf, subdir)``, where: - ``pkg_xml`` is an ``ElementTree.Element`` holding the xml for a package - ``zf`` is a ``zipfile.ZipFile`` for the package's contents. - ``subdir`` is the subdirectory (relative to ``root``) where the package w...
def _find_packages(root): """ Helper for ``build_index()``: Yield a list of tuples ``(pkg_xml, zf, subdir)``, where: - ``pkg_xml`` is an ``ElementTree.Element`` holding the xml for a package - ``zf`` is a ``zipfile.ZipFile`` for the package's contents. - ``subdir`` is the subdirectory (relative to...
Return a constant describing the status of the given package or collection. Status can be one of ``INSTALLED``, ``NOT_INSTALLED``, ``STALE``, or ``PARTIAL``.
def status(self, info_or_id, download_dir=None): """ Return a constant describing the status of the given package or collection. Status can be one of ``INSTALLED``, ``NOT_INSTALLED``, ``STALE``, or ``PARTIAL``. """ if download_dir is None: download_dir = self._download_dir info = self._info...
Re-download any packages whose status is STALE.
def update(self, quiet=False, prefix='[polyglot_data] '): """ Re-download any packages whose status is STALE. """ self.clear_status_cache() for pkg in self.packages(): if self.status(pkg) == self.STALE: self.download(pkg, quiet=quiet, prefix=prefix)
A helper function that ensures that self._index is up-to-date. If the index is older than self.INDEX_TIMEOUT, then download it again.
def _update_index(self, url=None): """A helper function that ensures that self._index is up-to-date. If the index is older than self.INDEX_TIMEOUT, then download it again.""" # Check if the index is aleady up-to-date. If so, do nothing. if not (self._index is None or url is not None or tim...
Return the ``Package`` or ``Collection`` record for the given item.
def info(self, id): """Return the ``Package`` or ``Collection`` record for the given item.""" #self._update_index() # This is commented because it leads to # excessive network load if id in self._packages: return self._packages[id] if id in self._collections: return self...
Return the collection that represents a specific language or task. Args: lang (string): Language code. task (string): Task name.
def get_collection(self, lang=None, task=None): """ Return the collection that represents a specific language or task. Args: lang (string): Language code. task (string): Task name. """ if lang: id = "{}{}".format(Downloader.LANG_PREFIX, lang) elif task: id = "{}{}".format(Downloader.TAS...
Return True if polyglot supports the language. Args: lang (string): Language code.
def supported_language(lang): """Return True if polyglot supports the language. Args: lang (string): Language code. """ try: self.get_collection(lang=lang) return True except LanguageNotSupported as e: return False
Languages that are covered by a specific task. Args: task (string): Task name.
def supported_languages(self, task=None): """Languages that are covered by a specific task. Args: task (string): Task name. """ if task: collection = self.get_collection(task=task) return [isoLangs[x.id.split('.')[1]]["name"] for x in collectio...
Languages that are covered by a specific task. Args: lang (string): Language code name.
def supported_tasks(self, lang=None): """Languages that are covered by a specific task. Args: lang (string): Language code name. """ if lang: collection = self.get_collection(lang=lang) return [x.id.split('.')[0] for x in collection.packages] else: return [x.name.split()[0] ...
Return the XML info record for the given item
def xmlinfo(self, id): """Return the XML info record for the given item""" self._update_index() for package in self._index.findall('packages/package'): if package.get('id') == id: return package for collection in self._index.findall('collections/collection'): if collection.get('id') ...
Set a new URL for the data server. If we're unable to contact the given url, then the original url is kept.
def _set_url(self, url): """ Set a new URL for the data server. If we're unable to contact the given url, then the original url is kept. """ original_url = self._url try: self._update_index(url) except: self._url = original_url raise
Transliterate a string from English to the target language.
def _decoder(self): """Transliterate a string from English to the target language.""" if self.target_lang == 'en': return Transliterator._dummy_coder else: weights = load_transliteration_table(self.target_lang) decoder_weights = weights["decoder"] return Transliterator._transliterate...
Transliterate a string from the input language to English.
def _encoder(self): """Transliterate a string from the input language to English.""" if self.source_lang == 'en': return Transliterator._dummy_coder else: weights = load_transliteration_table(self.source_lang) encoder_weights = weights["encoder"] return Transliterator._transliterate_...
Transliterate the word from its source language to the target one. The method works by encoding the word into English then decoding the new Enlgish word to the target language.
def transliterate(self, word): """Transliterate the word from its source language to the target one. The method works by encoding the word into English then decoding the new Enlgish word to the target language. """ encoded_word = self.encoder(word) decoded_word = self.decoder(encoded_word) ...
Return a list of tokens, using this blob's tokenizer object (defaults to :class:`WordTokenizer <textblob.tokenizers.WordTokenizer>`).
def tokens(self): """Return a list of tokens, using this blob's tokenizer object (defaults to :class:`WordTokenizer <textblob.tokenizers.WordTokenizer>`). """ seq = self.word_tokenizer.transform(Sequence(self.raw)) return WordList(seq.tokens(), parent=self, language=self.language.code)
Return the polarity score as a float within the range [-1.0, 1.0]
def polarity(self): """Return the polarity score as a float within the range [-1.0, 1.0] """ scores = [w.polarity for w in self.words if w.polarity != 0] if not scores: return 0.0 return sum(scores) / float(len(scores))
Transliterate the string to the target language.
def transliterate(self, target_language="en"): """Transliterate the string to the target language.""" return WordList([w.transliterate(target_language) for w in self.words], language=target_language, parent=self)
Returns a list of entities for this blob.
def entities(self): """Returns a list of entities for this blob.""" start = 0 end = 0 prev_tag = u'O' chunks = [] for i, (w, tag) in enumerate(self.ne_chunker.annotate(self.words)): if tag != prev_tag: if prev_tag == u'O': start = i else: chunks.append(C...
Returns an list of tuples of the form (word, POS tag). Example: :: [('At', 'ADP'), ('eight', 'NUM'), ("o'clock", 'NOUN'), ('on', 'ADP'), ('Thursday', 'NOUN'), ('morning', 'NOUN')] :rtype: list of tuples
def pos_tags(self): """Returns an list of tuples of the form (word, POS tag). Example: :: [('At', 'ADP'), ('eight', 'NUM'), ("o'clock", 'NOUN'), ('on', 'ADP'), ('Thursday', 'NOUN'), ('morning', 'NOUN')] :rtype: list of tuples """ tagged_words = [] for word,t in self.pos_tagge...
Returns an list of tuples of the form (word, POS tag), using transfer POS tagger
def transfer_pos_tags(self): """Returns an list of tuples of the form (word, POS tag), using transfer POS tagger""" tagged_words = [] for word,t in self.transfer_pos_tagger.annotate(self.words): word.pos_tag = t tagged_words.append((word, t)) return tagged_words
Dictionary of word frequencies in this text.
def word_counts(self): """Dictionary of word frequencies in this text. """ counts = defaultdict(int) for word in self.words: counts[word] += 1 return counts
Dictionary of noun phrase frequencies in this text.
def np_counts(self): """Dictionary of noun phrase frequencies in this text. """ counts = defaultdict(int) for phrase in self.noun_phrases: counts[phrase] += 1 return counts
Return a list of n-grams (tuples of n successive words) for this blob. :rtype: List of :class:`WordLists <WordList>`
def ngrams(self, n=3): """Return a list of n-grams (tuples of n successive words) for this blob. :rtype: List of :class:`WordLists <WordList>` """ if n <= 0: return [] grams = [WordList(self.words[i:i+n], parent=self) for i in range(len(self.words) - n + 1)] r...
Attempt to correct the spelling of a blob. .. versionadded:: 0.6.0 :rtype: :class:`BaseBlob <BaseBlob>`
def correct(self): """Attempt to correct the spelling of a blob. .. versionadded:: 0.6.0 :rtype: :class:`BaseBlob <BaseBlob>` """ # regex matches: contraction or word or punctuation or whitespace tokens = nltk.tokenize.regexp_tokenize(self.raw, "\w*('\w*)+|\w+|[^\w\s]|\s") corrected = (Word(...
Behaves like the built-in str.split() except returns a WordList. :rtype: :class:`WordList <WordList>`
def split(self, sep=None, maxsplit=sys.maxsize): """Behaves like the built-in str.split() except returns a WordList. :rtype: :class:`WordList <WordList>` """ return WordList(self._strkey().split(sep, maxsplit), parent=self)
Transliterate the string to the target language.
def transliterate(self, target_language="en"): """Transliterate the string to the target language.""" t = Transliterator(source_lang=self.language, target_lang=target_language) return t.transliterate(self.string)
Get the count of a word or phrase `s` within this WordList. :param strg: The string to count. :param case_sensitive: A boolean, whether or not the search is case-sensitive.
def count(self, strg, case_sensitive=False, *args, **kwargs): """Get the count of a word or phrase `s` within this WordList. :param strg: The string to count. :param case_sensitive: A boolean, whether or not the search is case-sensitive. """ if not case_sensitive: return [word.lower() for wo...
Append an object to end. If the object is a string, appends a :class:`Word <Word>` object.
def append(self, obj): """Append an object to end. If the object is a string, appends a :class:`Word <Word>` object. """ if isinstance(obj, basestring): return self._collection.append(Word(obj)) else: return self._collection.append(obj)
Extend WordList by appending elements from ``iterable``. If an element is a string, appends a :class:`Word <Word>` object.
def extend(self, iterable): """Extend WordList by appending elements from ``iterable``. If an element is a string, appends a :class:`Word <Word>` object. """ [self._collection.append(Word(e) if isinstance(e, basestring) else e) for e in iterable] return self
Calculates the sentiment of an entity as it appears in text.
def _sentiment(self, distance=True): """Calculates the sentiment of an entity as it appears in text.""" sum_pos = 0 sum_neg = 0 text = self.parent entity_positions = range(self.start, self.end) non_entity_positions = set(range(len(text.words))).difference(entity_positions) if not distance: ...
The dict representation of this sentence.
def dict(self): '''The dict representation of this sentence.''' return { 'raw': self.raw, 'start': self.start, 'end': self.end, 'entities': [(e.tag, e) for e in self.entities], 'tokens': self.tokens, 'words': self.words, 'pos_tags': self.pos_tags, ...
Return a json representation (str) of this blob. Takes the same arguments as json.dumps. .. versionadded:: 0.5.1
def to_json(self, *args, **kwargs): '''Return a json representation (str) of this blob. Takes the same arguments as json.dumps. .. versionadded:: 0.5.1 ''' try: import ujson as json except ImportError: import json return json.dumps(self.serialized, *args, **kwargs)
Returns a list of Sentence objects from the raw text.
def _create_sentence_objects(self): '''Returns a list of Sentence objects from the raw text. ''' sentence_objects = [] sent_tokenizer = SentenceTokenizer(locale=self.language.code) seq = Sequence(self.raw) seq = sent_tokenizer.transform(seq) for start_index, end_index in zip(seq.idx[:-1], se...
Decide which language is used to write the text. The method tries first to detect the language with high reliability. If that is not possible, the method switches to best effort strategy. Args: text (string): A snippet of text, the longer it is the more reliable we can detect t...
def detect(self, text): """Decide which language is used to write the text. The method tries first to detect the language with high reliability. If that is not possible, the method switches to best effort strategy. Args: text (string): A snippet of text, the longer it is the more reliable we ...
Return filename that contains specific language resource name. Args: name (string): Name of the resource. lang (string): language code to be loaded.
def locate_resource(name, lang, filter=None): """Return filename that contains specific language resource name. Args: name (string): Name of the resource. lang (string): language code to be loaded. """ task_dir = resource_dir.get(name, name) package_id = u"{}.{}".format(task_dir, lang) p = path.joi...
Return a word embeddings object for `lang` and of type `type` Args: lang (string): language code. task (string): parameters that define task. type (string): skipgram, cw, cbow ... noramlized (boolean): returns noramlized word embeddings vectors.
def load_embeddings(lang="en", task="embeddings", type="cw", normalize=False): """Return a word embeddings object for `lang` and of type `type` Args: lang (string): language code. task (string): parameters that define task. type (string): skipgram, cw, cbow ... noramlized (boolean): returns noramli...
Return a CountedVocabulary object. Args: lang (string): language code. type (string): wiki,...
def load_vocabulary(lang="en", type="wiki"): """Return a CountedVocabulary object. Args: lang (string): language code. type (string): wiki,... """ src_dir = "{}_vocab".format(type) p = locate_resource(src_dir, lang) return CountedVocabulary.from_vocabfile(p)
Return a named entity extractor parameters for `lang` and of version `version` Args: lang (string): language code. version (string): version of the parameters to be used.
def load_ner_model(lang="en", version="2"): """Return a named entity extractor parameters for `lang` and of version `version` Args: lang (string): language code. version (string): version of the parameters to be used. """ src_dir = "ner{}".format(version) p = locate_resource(src_dir, lang) fh = _op...
Return a part of speech tagger parameters for `lang` and of version `version` Args: lang (string): language code. version (string): version of the parameters to be used.
def load_pos_model(lang="en", version="2"): """Return a part of speech tagger parameters for `lang` and of version `version` Args: lang (string): language code. version (string): version of the parameters to be used. """ src_dir = "pos{}".format(version) p = locate_resource(src_dir, lang) fh = _ope...
Return a morfessor model for `lang` and of version `version` Args: lang (string): language code. version (string): version of the parameters to be used.
def load_morfessor_model(lang="en", version="2"): """Return a morfessor model for `lang` and of version `version` Args: lang (string): language code. version (string): version of the parameters to be used. """ src_dir = "morph{}".format(version) p = locate_resource(src_dir, lang) file_handler = _op...
Return a morfessor model for `lang` and of version `version` Args: lang (string): language code. version (string): version of the parameters to be used.
def load_transliteration_table(lang="en", version="2"): """Return a morfessor model for `lang` and of version `version` Args: lang (string): language code. version (string): version of the parameters to be used. """ src_dir = "transliteration{}".format(version) p = locate_resource(src_dir, lang) fi...
Calculate the vocabulary.
def vocab_counter(args): """Calculate the vocabulary.""" if isinstance(args.input, TextFiles): v = CountedVocabulary.from_textfiles(args.input, workers=args.workers) else: v = CountedVocabulary.from_textfile(args.input, workers=args.workers) if args.min_count > 1: v = v.min_count(args.min_count) ...
Detect the language of each line.
def detect(args): """ Detect the language of each line.""" for l in args.input: if l.strip(): _print("{:<20}{}".format(Detector(l).language.name, l.strip()))
Chunk named entities.
def tag(tagger, args): """Chunk named entities.""" for l in args.input: words = l.strip().split() line_annotations = [u"{:<16}{:<5}".format(w,p) for w, p in tagger.annotate(words)] _print(u"\n".join(line_annotations)) _print(u"")
Transliterate words according to the target language.
def transliterate(args): """Transliterate words according to the target language.""" t = Transliterator(source_lang=args.lang, target_lang=args.target) for l in args.input: words = l.strip().split() line_annotations = [u"{:<16}{:<16}".format(w, t.transliterate(w)) for w in words] ...
Segment words according to their morphemes.
def morphemes(args): """Segment words according to their morphemes.""" morfessor = load_morfessor_model(lang=args.lang) for l in args.input: words = l.strip().split() morphemes = [(w, u"_".join(morfessor.viterbi_segment(w)[0])) for w in words] line_annotations = [u"{:<16}{:<5}".format(w,p) for w, p in...
Chunk named entities.
def ner_chunk(args): """Chunk named entities.""" chunker = NEChunker(lang=args.lang) tag(chunker, args)
Tag words with their part of speech.
def pos_tag(args): """Tag words with their part of speech.""" tagger = POSTagger(lang=args.lang) tag(tagger, args)
Download polyglot packages and models.
def download(args): """ Download polyglot packages and models.""" downloader = Downloader(server_index_url = args.server_index_url) if args.packages: for pkg_id in args.packages: rv = downloader.download(info_or_id=unicode(pkg_id), download_dir=args.dir, quiet=args.quiet,...
Open file object given filenames, open files or even archives.
def _open(file_, mode='r'): """Open file object given filenames, open files or even archives.""" if isinstance(file_, string_types): _, ext = path.splitext(file_) if ext in {'.bz2', '.gz'}: s = tarfile.open(file_) return s.extractfile(s.next()) else: return open(file_, mode) return f...
Unpickle methods properly, including class methods.
def _unpickle_method(func_name, obj, cls): """Unpickle methods properly, including class methods.""" if obj is None: return cls.__dict__[func_name].__get__(obj, cls) for cls in cls.__mro__: try: func = cls.__dict__[func_name] except KeyError: pass else: break return func.__get...
Determine a link to online source for a class/method/function This is called by sphinx.ext.linkcode An example with a long-untouched module that everyone has >>> _linkcode_resolve('py', {'module': 'tty', ... 'fullname': 'setraw'}, ... package='tty', ....
def _linkcode_resolve(domain, info, package, url_fmt, revision): """Determine a link to online source for a class/method/function This is called by sphinx.ext.linkcode An example with a long-untouched module that everyone has >>> _linkcode_resolve('py', {'module': 'tty', ... ...
Returns a linkcode_resolve function for the given URL format revision is a git commit reference (hash or name) package is the name of the root module of the package url_fmt is along the lines of ('https://github.com/USER/PROJECT/' 'blob/{revision}/{package}/' ...
def make_linkcode_resolve(package, url_fmt): """Returns a linkcode_resolve function for the given URL format revision is a git commit reference (hash or name) package is the name of the root module of the package url_fmt is along the lines of ('https://github.com/USER/PROJECT/' ...
Counts the word frequences in a list of sentences. Note: This is a helper function for parallel execution of `Vocabulary.from_text` method.
def count(lines): """ Counts the word frequences in a list of sentences. Note: This is a helper function for parallel execution of `Vocabulary.from_text` method. """ words = [w for l in lines for w in l.strip().split()] return Counter(words)
Guarantees that all textual symbols are unicode. Note: We do not convert numbers, only strings to unicode. We assume that the strings are encoded in utf-8.
def sanitize_words(self, words): """Guarantees that all textual symbols are unicode. Note: We do not convert numbers, only strings to unicode. We assume that the strings are encoded in utf-8. """ _words = [] for w in words: if isinstance(w, string_types) and not isinstance(w, unic...
Construct a CountedVocabulary out of a vocabulary file. Note: File has the following format word1 word2
def from_vocabfile(cls, filename): """ Construct a CountedVocabulary out of a vocabulary file. Note: File has the following format word1 word2 """ words = [x.strip() for x in _open(filename, 'r').read().splitlines()] return cls(words=words)
Count the set of words appeared in a text file. Args: textfile (string): The name of the text file or `TextFile` object. min_count (integer): Minimum number of times a word/token appeared in the document to be considered part of the vocabulary. workers (integer): Number of parall...
def from_textfile(cls, textfile, workers=1, job_size=1000): """ Count the set of words appeared in a text file. Args: textfile (string): The name of the text file or `TextFile` object. min_count (integer): Minimum number of times a word/token appeared in the document to be consider...
Returns a vocabulary with the most frequent `k` words. Args: k (integer): specifies the top k most frequent words to be returned.
def most_frequent(self, k): """ Returns a vocabulary with the most frequent `k` words. Args: k (integer): specifies the top k most frequent words to be returned. """ word_count = {w:self.word_count[w] for w in self.words[:k]} return CountedVocabulary(word_count=word_count)
Returns a vocabulary after eliminating the words that appear < `n`. Args: n (integer): specifies the minimum word frequency allowed.
def min_count(self, n=1): """ Returns a vocabulary after eliminating the words that appear < `n`. Args: n (integer): specifies the minimum word frequency allowed. """ word_count = {w:c for w,c in iteritems(self.word_count) if c >= n} return CountedVocabulary(word_count=word_count)
Construct a CountedVocabulary out of a vocabulary file. Note: File has the following format word1 count1 word2 count2
def from_vocabfile(filename): """ Construct a CountedVocabulary out of a vocabulary file. Note: File has the following format word1 count1 word2 count2 """ word_count = [x.strip().split() for x in _open(filename, 'r').read().splitlines()] word_count = {w:in...
Split into subsequences according to `sequence`.
def split(self, sequence): """ Split into subsequences according to `sequence`.""" major_idx = sequence.idx idx2 = 0 for start, end in zip(major_idx[:-1], major_idx[1:]): idx1 = self.idx.index(start, idx2) idx2 = self.idx.index(end, idx2) seq = Sequence(self.text[start:end]) seq...