API Reference — textblob-de 0.4.3 documentation

# API Reference

## Blob Classes

Wrappers for various units of text.

This includes the main `TextBlobDE`, `Word`, and `WordList` classes.

Whenever possible, classes are inherited from the main TextBlob library, but in many cases, the models for German have to be initialised here in `textblob_de.blob`, resulting in a lot of duplicate code. The main reason are the `Word` objects. If they are generated from an inherited class, they will use the English models (e.g. for `pluralize`/`singularize`) used in the main library.

Example usage:

    >>> from textblob_de import TextBlobDE
    >>> b = TextBlobDE("Einfach ist besser als kompliziert.")
    >>> b.tags
    [('Einfach', 'RB'), ('ist', 'VB'), ('besser', 'RB'), ('als', 'IN'), ('kompliziert', 'JJ')]
    >>> b.noun_phrases
    WordList([])
    >>> b.words
    WordList(['Einfach', 'ist', 'besser', 'als', 'kompliziert'])

class `textblob_de.blob.` `BaseBlob`(text, tokenizer=None, pos_tagger=None, np_extractor=None, analyzer=None, parser=None, classifier=None, clean_html=False)

  `BaseBlob` class initialised with German default models:

  An abstract base class that all textblob classes will inherit from. Includes words, POS tag, NP, and word count properties. Also includes basic dunder and string methods for making objects like Python strings.

  Parameters: | text (str) – A string. tokenizer – (optional) A tokenizer instance. If `None`, defaults to `NLTKPunktTokenizer()`. np_extractor – (optional) An NPExtractor instance. If `None`, defaults to `PatternParserNPExtractor()`. pos_tagger – (optional) A Tagger instance. If `None`, defaults to `PatternTagger`. analyzer – (optional) A sentiment analyzer. If `None`, defaults to `PatternAnalyzer`. classifier – (optional) A classifier.

  Changed in version 0.6.0: `clean_html` parameter deprecated, as it was in NLTK.

  `classify`()

    Classify the blob using the blob’s `classifier`.

  `correct`()

    Attempt to correct the spelling of a blob.

    New in version 0.6.0: (`textblob`)

    Return type: | `BaseBlob`

  `detect_language`()

    Detect the blob’s language using the Google Translate API.

    Requires an internet connection.

    Usage:

        >>> b = TextBlob("bonjour")
        >>> b.detect_language()
        u'fr'

    Language code reference:
      https://developers.google.com/translate/v2/using_rest#language-params

    New in version 0.5.0.

    Return type: | str

  `ends_with`(suffix, start=0, end=9223372036854775807)

    Returns True if the blob ends with the given suffix.

  `endswith`(suffix, start=0, end=9223372036854775807)

    Returns True if the blob ends with the given suffix.

  `find`(sub, start=0, end=9223372036854775807)

    Behaves like the built-in str.find() method. Returns an integer, the index of the first occurrence of the substring argument sub in the sub-string given by [start:end].

  `format`(*args, **kwargs)

    Perform a string formatting operation, like the built-in str.format(*args, **kwargs). Returns a blob object.

  `index`(sub, start=0, end=9223372036854775807)

    Like blob.find() but raise ValueError when the substring is not found.

  `join`(iterable)

    Behaves like the built-in str.join(iterable) method, except returns a blob object.

    Returns a blob which is the concatenation of the strings or blobs in the iterable.

  `lower`()

    Like str.lower(), returns new object with all lower-cased characters.

  `ngrams`(n=3)

    Return a list of n-grams (tuples of n successive words) for this blob.

    Return type: | List of `WordLists`

  `noun_phrases`

    Returns a list of noun phrases for this blob.

  `np_counts`

    Dictionary of noun phrase frequencies in this text.

  `parse`(parser=None)

    Parse the text.

    Parameters: | parser – (optional) A parser instance. If `None`, defaults to this blob’s default parser.

    New in version 0.6.0.

  `polarity`

    Return the polarity score as a float within the range [-1.0, 1.0]

    Return type: | float

  `pos_tags`

    Returns an list of tuples of the form (word, POS tag).

    Example:

        [('At', 'IN'), ('eight', 'CD'), ("o'clock", 'JJ'), ('on', 'IN'),
                ('Thursday', 'NNP'), ('morning', 'NN')]

    Return type: | list of tuples

  `replace`(old, new, count=9223372036854775807)

    Return a new blob object with all the occurence of old replaced by new.

  `rfind`(sub, start=0, end=9223372036854775807)

    Behaves like the built-in str.rfind() method. Returns an integer, the index of he last (right-most) occurence of the substring argument sub in the sub-sequence given by [start:end].

  `rindex`(sub, start=0, end=9223372036854775807)

    Like blob.rfind() but raise ValueError when substring is not found.

  `sentiment`

    Return a tuple of form (polarity, subjectivity ) where polarity is a float within the range [-1.0, 1.0] and subjectivity is a float within the range [0.0, 1.0] where 0.0 is very objective and 1.0 is very subjective.

    Return type: | namedtuple of the form `Sentiment(polarity, subjectivity)`

  `sentiment_assessments`

    Return a tuple of form (polarity, subjectivity, assessments ) where polarity is a float within the range [-1.0, 1.0], subjectivity is a float within the range [0.0, 1.0] where 0.0 is very objective and 1.0 is very subjective, and assessments is a list of polarity and subjectivity scores for the assessed tokens.

    Return type: | namedtuple of the form `Sentiment(polarity, subjectivity, assessments)`

  `split`(sep=None, maxsplit=9223372036854775807)

    Behaves like the built-in str.split() except returns a WordList.

    Return type: | `WordList`

  `starts_with`(prefix, start=0, end=9223372036854775807)

    Returns True if the blob starts with the given prefix.

  `startswith`(prefix, start=0, end=9223372036854775807)

    Returns True if the blob starts with the given prefix.

  `strip`(chars=None)

    Behaves like the built-in str.strip([chars]) method. Returns an object with leading and trailing whitespace removed.

  `subjectivity`

    Return the subjectivity score as a float within the range [0.0, 1.0] where 0.0 is very objective and 1.0 is very subjective.

    Return type: | float

  `tags`

    Returns an list of tuples of the form (word, POS tag).

    Example:

        [('At', 'IN'), ('eight', 'CD'), ("o'clock", 'JJ'), ('on', 'IN'),
                ('Thursday', 'NNP'), ('morning', 'NN')]

    Return type: | list of tuples

  `title`()

    Returns a blob object with the text in title-case.

  `tokenize`(tokenizer=None)

    Return a list of tokens, using `tokenizer`.

    Parameters: | tokenizer – (optional) A tokenizer object. If None, defaults to this blob’s default tokenizer.

  `tokens`

    Return a list of tokens, using this blob’s tokenizer object (defaults to `WordTokenizer`).

  `translate`(from_lang=None, to='de')

    Translate the blob to another language.

  `upper`()

    Like str.upper(), returns new object with all upper-cased characters.

  `word_counts`

    Dictionary of word frequencies in this text.

  `words`

    Return a list of word tokens. This excludes punctuation characters. If you want to include punctuation characters, access the `tokens` property.

    Returns: | A `WordList` of word tokens.

class `textblob_de.blob.` `BlobberDE`(tokenizer=None, pos_tagger=None, np_extractor=None, analyzer=None, parser=None, classifier=None)

  A factory for TextBlobs that all share the same tagger, tokenizer, parser, classifier, and np_extractor.

  Usage:

      >>> from textblob_de import BlobberDE
      >>> from textblob_de.taggers import PatternTagger
      >>> from textblob.tokenizers import PatternTokenizer
      >>> tb = Blobber(pos_tagger=PatternTagger(), tokenizer=PatternTokenizer())
      >>> blob1 = tb("Das ist ein Blob.")
      >>> blob2 = tb("Dieser Blob benutzt die selben Tagger und Tokenizer.")
      >>> blob1.pos_tagger is blob2.pos_tagger
      True

  Parameters: | text (str) – A string. tokenizer – (optional) A tokenizer instance. If `None`, defaults to `NLTKPunktTokenizer()`. np_extractor – (optional) An NPExtractor instance. If `None`, defaults to `PatternParserNPExtractor()`. pos_tagger – (optional) A Tagger instance. If `None`, defaults to `PatternTagger`. analyzer – (optional) A sentiment analyzer. If `None`, defaults to `PatternAnalyzer`. classifier – (optional) A classifier.

  New in version 0.4.0: (`textblob`)

class `textblob_de.blob.` `Sentence`(sentence, start_index=0, end_index=None, *args, **kwargs)

  A sentence within a TextBlob. Inherits from `BaseBlob`.

  Parameters: | sentence – A string, the raw sentence. start_index – An int, the index where this sentence begins in a TextBlob. If not given, defaults to 0. end_index – An int, the index where this sentence ends in a TextBlob. If not given, defaults to the length of the sentence - 1.

  `classify`()

    Classify the blob using the blob’s `classifier`.

  `correct`()

    Attempt to correct the spelling of a blob.

    New in version 0.6.0: (`textblob`)

    Return type: | `BaseBlob`

  `detect_language`()

    Detect the blob’s language using the Google Translate API.

    Requires an internet connection.

    Usage:

        >>> b = TextBlob("bonjour")
        >>> b.detect_language()
        u'fr'

    Language code reference:
      https://developers.google.com/translate/v2/using_rest#language-params

    New in version 0.5.0.

    Return type: | str

  `dict`

    The dict representation of this sentence.

  `end` = None

    The end index within a textBlob

  `end_index` = None

    The end index within a textBlob

  `ends_with`(suffix, start=0, end=9223372036854775807)

    Returns True if the blob ends with the given suffix.

  `endswith`(suffix, start=0, end=9223372036854775807)

    Returns True if the blob ends with the given suffix.

  `find`(sub, start=0, end=9223372036854775807)

    Behaves like the built-in str.find() method. Returns an integer, the index of the first occurrence of the substring argument sub in the sub-string given by [start:end].

  `format`(*args, **kwargs)

    Perform a string formatting operation, like the built-in str.format(*args, **kwargs). Returns a blob object.

  `index`(sub, start=0, end=9223372036854775807)

    Like blob.find() but raise ValueError when the substring is not found.

  `join`(iterable)

    Behaves like the built-in str.join(iterable) method, except returns a blob object.

    Returns a blob which is the concatenation of the strings or blobs in the iterable.

  `lower`()

    Like str.lower(), returns new object with all lower-cased characters.

  `ngrams`(n=3)

    Return a list of n-grams (tuples of n successive words) for this blob.

    Return type: | List of `WordLists`

  `noun_phrases`

    Returns a list of noun phrases for this blob.

  `np_counts`

    Dictionary of noun phrase frequencies in this text.

  `parse`(parser=None)

    Parse the text.

    Parameters: | parser – (optional) A parser instance. If `None`, defaults to this blob’s default parser.

    New in version 0.6.0.

  `polarity`

    Return the polarity score as a float within the range [-1.0, 1.0]

    Return type: | float

  `pos_tags`

    Returns an list of tuples of the form (word, POS tag).

    Example:

        [('At', 'IN'), ('eight', 'CD'), ("o'clock", 'JJ'), ('on', 'IN'),
                ('Thursday', 'NNP'), ('morning', 'NN')]

    Return type: | list of tuples

  `replace`(old, new, count=9223372036854775807)

    Return a new blob object with all the occurence of old replaced by new.

  `rfind`(sub, start=0, end=9223372036854775807)

    Behaves like the built-in str.rfind() method. Returns an integer, the index of he last (right-most) occurence of the substring argument sub in the sub-sequence given by [start:end].

  `rindex`(sub, start=0, end=9223372036854775807)

    Like blob.rfind() but raise ValueError when substring is not found.

  `sentiment`

    Return a tuple of form (polarity, subjectivity ) where polarity is a float within the range [-1.0, 1.0] and subjectivity is a float within the range [0.0, 1.0] where 0.0 is very objective and 1.0 is very subjective.

    Return type: | namedtuple of the form `Sentiment(polarity, subjectivity)`

  `sentiment_assessments`

    Return a tuple of form (polarity, subjectivity, assessments ) where polarity is a float within the range [-1.0, 1.0], subjectivity is a float within the range [0.0, 1.0] where 0.0 is very objective and 1.0 is very subjective, and assessments is a list of polarity and subjectivity scores for the assessed tokens.

    Return type: | namedtuple of the form `Sentiment(polarity, subjectivity, assessments)`

  `split`(sep=None, maxsplit=9223372036854775807)

    Behaves like the built-in str.split() except returns a WordList.

    Return type: | `WordList`

  `start` = None

    The start index within a TextBlob

  `start_index` = None

    The start index within a TextBlob

  `starts_with`(prefix, start=0, end=9223372036854775807)

    Returns True if the blob starts with the given prefix.

  `startswith`(prefix, start=0, end=9223372036854775807)

    Returns True if the blob starts with the given prefix.

  `strip`(chars=None)

    Behaves like the built-in str.strip([chars]) method. Returns an object with leading and trailing whitespace removed.

  `subjectivity`

    Return the subjectivity score as a float within the range [0.0, 1.0] where 0.0 is very objective and 1.0 is very subjective.

    Return type: | float

  `tags`

    Returns an list of tuples of the form (word, POS tag).

    Example:

        [('At', 'IN'), ('eight', 'CD'), ("o'clock", 'JJ'), ('on', 'IN'),
                ('Thursday', 'NNP'), ('morning', 'NN')]

    Return type: | list of tuples

  `title`()

    Returns a blob object with the text in title-case.

  `tokenize`(tokenizer=None)

    Return a list of tokens, using `tokenizer`.

    Parameters: | tokenizer – (optional) A tokenizer object. If None, defaults to this blob’s default tokenizer.

  `tokens`

    Return a list of tokens, using this blob’s tokenizer object (defaults to `WordTokenizer`).

  `translate`(from_lang=None, to='de')

    Translate the blob to another language.

  `upper`()

    Like str.upper(), returns new object with all upper-cased characters.

  `word_counts`

    Dictionary of word frequencies in this text.

  `words`

    Return a list of word tokens. This excludes punctuation characters. If you want to include punctuation characters, access the `tokens` property.

    Returns: | A `WordList` of word tokens.

class `textblob_de.blob.` `TextBlobDE`(text, tokenizer=None, pos_tagger=None, np_extractor=None, analyzer=None, parser=None, classifier=None, clean_html=False)

  `TextBlob` class initialised with German default models:

  Parameters: | text (str) – A string. tokenizer – (optional) A tokenizer instance. If `None`, defaults to `NLTKPunktTokenizer()`. np_extractor – (optional) An NPExtractor instance. If `None`, defaults to `PatternParserNPExtractor()`. pos_tagger – (optional) A Tagger instance. If `None`, defaults to `PatternTagger`. analyzer – (optional) A sentiment analyzer. If `None`, defaults to `PatternAnalyzer`. classifier – (optional) A classifier.

  `classify`()

    Classify the blob using the blob’s `classifier`.

  `correct`()

    Attempt to correct the spelling of a blob.

    New in version 0.6.0: (`textblob`)

    Return type: | `BaseBlob`

  `detect_language`()

    Detect the blob’s language using the Google Translate API.

    Requires an internet connection.

    Usage:

        >>> b = TextBlob("bonjour")
        >>> b.detect_language()
        u'fr'

    Language code reference:
      https://developers.google.com/translate/v2/using_rest#language-params

    New in version 0.5.0.

    Return type: | str

  `ends_with`(suffix, start=0, end=9223372036854775807)

    Returns True if the blob ends with the given suffix.

  `endswith`(suffix, start=0, end=9223372036854775807)

    Returns True if the blob ends with the given suffix.

  `find`(sub, start=0, end=9223372036854775807)

    Behaves like the built-in str.find() method. Returns an integer, the index of the first occurrence of the substring argument sub in the sub-string given by [start:end].

  `format`(*args, **kwargs)

    Perform a string formatting operation, like the built-in str.format(*args, **kwargs). Returns a blob object.

  `index`(sub, start=0, end=9223372036854775807)

    Like blob.find() but raise ValueError when the substring is not found.

  `join`(iterable)

    Behaves like the built-in str.join(iterable) method, except returns a blob object.

    Returns a blob which is the concatenation of the strings or blobs in the iterable.

  `json`

    The json representation of this blob.

    Changed in version 0.5.1: Made `json` a property instead of a method to restore backwards compatibility that was broken after version 0.4.0.

  `lower`()

    Like str.lower(), returns new object with all lower-cased characters.

  `ngrams`(n=3)

    Return a list of n-grams (tuples of n successive words) for this blob.

    Return type: | List of `WordLists`

  `noun_phrases`

    Returns a list of noun phrases for this blob.

  `np_counts`

    Dictionary of noun phrase frequencies in this text.

  `parse`(parser=None)

    Parse the text.

    Parameters: | parser – (optional) A parser instance. If `None`, defaults to this blob’s default parser.

    New in version 0.6.0.

  `polarity`

    Return the polarity score as a float within the range [-1.0, 1.0]

    Return type: | float

  `pos_tags`

    Returns an list of tuples of the form (word, POS tag).

    Example:

        [('At', 'IN'), ('eight', 'CD'), ("o'clock", 'JJ'), ('on', 'IN'),
                ('Thursday', 'NNP'), ('morning', 'NN')]

    Return type: | list of tuples

  `raw_sentences`

    List of strings, the raw sentences in the blob.

  `replace`(old, new, count=9223372036854775807)

    Return a new blob object with all the occurence of old replaced by new.

  `rfind`(sub, start=0, end=9223372036854775807)

    Behaves like the built-in str.rfind() method. Returns an integer, the index of he last (right-most) occurence of the substring argument sub in the sub-sequence given by [start:end].

  `rindex`(sub, start=0, end=9223372036854775807)

    Like blob.rfind() but raise ValueError when substring is not found.

  `sentences`

    Return list of `Sentence` objects.

  `sentiment`

    Return a tuple of form (polarity, subjectivity ) where polarity is a float within the range [-1.0, 1.0] and subjectivity is a float within the range [0.0, 1.0] where 0.0 is very objective and 1.0 is very subjective.

    Return type: | named tuple of the form `Sentiment(polarity=0.0, subjectivity=0.0)`

  `sentiment_assessments`

    Return a tuple of form (polarity, subjectivity, assessments ) where polarity is a float within the range [-1.0, 1.0], subjectivity is a float within the range [0.0, 1.0] where 0.0 is very objective and 1.0 is very subjective, and assessments is a list of polarity and subjectivity scores for the assessed tokens.

    Return type: | namedtuple of the form `Sentiment(polarity, subjectivity, assessments)`

  `serialized`

    Returns a list of each sentence’s dict representation.

  `split`(sep=None, maxsplit=9223372036854775807)

    Behaves like the built-in str.split() except returns a WordList.

    Return type: | `WordList`

  `starts_with`(prefix, start=0, end=9223372036854775807)

    Returns True if the blob starts with the given prefix.

  `startswith`(prefix, start=0, end=9223372036854775807)

    Returns True if the blob starts with the given prefix.

  `strip`(chars=None)

    Behaves like the built-in str.strip([chars]) method. Returns an object with leading and trailing whitespace removed.

  `subjectivity`

    Return the subjectivity score as a float within the range [0.0, 1.0] where 0.0 is very objective and 1.0 is very subjective.

    Return type: | float

  `tags`

    Returns an list of tuples of the form (word, POS tag).

    Example:

        [('At', 'IN'), ('eight', 'CD'), ("o'clock", 'JJ'), ('on', 'IN'),
                ('Thursday', 'NNP'), ('morning', 'NN')]

    Return type: | list of tuples

  `title`()

    Returns a blob object with the text in title-case.

  `to_json`(*args, **kwargs)

    Return a json representation (str) of this blob. Takes the same arguments as json.dumps.

    New in version 0.5.1: (`textblob`)

  `tokenize`(tokenizer=None)

    Return a list of tokens, using `tokenizer`.

    Parameters: | tokenizer – (optional) A tokenizer object. If None, defaults to this blob’s default tokenizer.

  `tokens`

    Return a list of tokens, using this blob’s tokenizer object (defaults to `WordTokenizer`).

  `translate`(from_lang=None, to='de')

    Translate the blob to another language.

  `upper`()

    Like str.upper(), returns new object with all upper-cased characters.

  `word_counts`

    Dictionary of word frequencies in this text.

  `words`

    Return a list of word tokens. This excludes punctuation characters. If you want to include punctuation characters, access the `tokens` property.

    Returns: | A `WordList` of word tokens.

class `textblob_de.blob.` `Word`(string, pos_tag=None)

  A simple word representation.

  Includes methods for inflection, translation, and WordNet integration.

  `capitalize`()

    Return a capitalized version of the string.

    More specifically, make the first character have upper case and the rest lower case.

  `casefold`()

    Return a version of the string suitable for caseless comparisons.

  `center`()

    Return a centered string of length width.

    Padding is done using the specified fill character (default is a space).

  `correct`()

    Correct the spelling of the word. Returns the word with the highest confidence using the spelling corrector.

    New in version 0.6.0: (`textblob`)

  `count`(sub[, start[, end]]) → int

    Return the number of non-overlapping occurrences of substring sub in string S[start:end]. Optional arguments start and end are interpreted as in slice notation.

  `define`(pos=None)

    Return a list of definitions for this word. Each definition corresponds to a synset for this word.

    Parameters: | pos – A part-of-speech tag to filter upon. If `None`, definitions for all parts of speech will be loaded.
    Return type: | List of strings

    New in version 0.7.0: (`textblob`)

  `definitions`

    The list of definitions for this word. Each definition corresponds to a synset.

    New in version 0.7.0: (`textblob`)

  `detect_language`()

    Detect the word’s language using Google’s Translate API.

    New in version 0.5.0: (`textblob`)

  `encode`()

    Encode the string using the codec registered for encoding.

    encoding
      The encoding in which to encode the string.
    errors
      The error handling scheme to use for encoding errors. The default is ‘strict’ meaning that encoding errors raise a UnicodeEncodeError. Other possible values are ‘ignore’, ‘replace’ and ‘xmlcharrefreplace’ as well as any other name registered with codecs.register_error that can handle UnicodeEncodeErrors.
  `endswith`(suffix[, start[, end]]) → bool

    Return True if S ends with the specified suffix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. suffix can also be a tuple of strings to try.

  `expandtabs`()

    Return a copy where all tab characters are expanded using spaces.

    If tabsize is not given, a tab size of 8 characters is assumed.

  `find`(sub[, start[, end]]) → int

    Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

    Return -1 on failure.

  `format`(*args, **kwargs) → str

    Return a formatted version of S, using substitutions from args and kwargs. The substitutions are identified by braces (‘{‘ and ‘}’).

  `format_map`(mapping) → str

    Return a formatted version of S, using substitutions from mapping. The substitutions are identified by braces (‘{‘ and ‘}’).

  `get_synsets`(pos=None)

    Return a list of Synset objects for this word.

    Parameters: | pos – A part-of-speech tag to filter upon. If `None`, all synsets for all parts of speech will be loaded.
    Return type: | list of Synsets

    New in version 0.7.0: (`textblob`)

  `index`(sub[, start[, end]]) → int

    Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

    Raises ValueError when the substring is not found.

  `isalnum`()

    Return True if the string is an alpha-numeric string, False otherwise.

    A string is alpha-numeric if all characters in the string are alpha-numeric and there is at least one character in the string.

  `isalpha`()

    Return True if the string is an alphabetic string, False otherwise.

    A string is alphabetic if all characters in the string are alphabetic and there is at least one character in the string.

  `isascii`()

    Return True if all characters in the string are ASCII, False otherwise.

    ASCII characters have code points in the range U+0000-U+007F. Empty string is ASCII too.

  `isdecimal`()

    Return True if the string is a decimal string, False otherwise.

    A string is a decimal string if all characters in the string are decimal and there is at least one character in the string.

  `isdigit`()

    Return True if the string is a digit string, False otherwise.

    A string is a digit string if all characters in the string are digits and there is at least one character in the string.

  `isidentifier`()

    Return True if the string is a valid Python identifier, False otherwise.

    Use keyword.iskeyword() to test for reserved identifiers such as “def” and “class”.

  `islower`()

    Return True if the string is a lowercase string, False otherwise.

    A string is lowercase if all cased characters in the string are lowercase and there is at least one cased character in the string.

  `isnumeric`()

    Return True if the string is a numeric string, False otherwise.

    A string is numeric if all characters in the string are numeric and there is at least one character in the string.

  `isprintable`()

    Return True if the string is printable, False otherwise.

    A string is printable if all of its characters are considered printable in repr() or if it is empty.

  `isspace`()

    Return True if the string is a whitespace string, False otherwise.

    A string is whitespace if all characters in the string are whitespace and there is at least one character in the string.

  `istitle`()

    Return True if the string is a title-cased string, False otherwise.

    In a title-cased string, upper- and title-case characters may only follow uncased characters and lowercase characters only cased ones.

  `isupper`()

    Return True if the string is an uppercase string, False otherwise.

    A string is uppercase if all cased characters in the string are uppercase and there is at least one cased character in the string.

  `join`()

    Concatenate any number of strings.

    The string whose method is called is inserted in between each given string. The result is returned as a new string.

    Example: ‘.’.join([‘ab’, ‘pq’, ‘rs’]) -> ‘ab.pq.rs’

  `lemma`

    Return the lemma of this word using Wordnet’s morphy function.

  `lemmatize`(pos=None)

    Return the lemma for a word using WordNet’s morphy function.

    Parameters: | pos – Part of speech to filter upon. If None, defaults to `_wordnet.NOUN`.

    New in version 0.8.1: (`textblob`)

  `ljust`()

    Return a left-justified string of length width.

    Padding is done using the specified fill character (default is a space).

  `lower`()

    Return a copy of the string converted to lowercase.

  `lstrip`()

    Return a copy of the string with leading whitespace removed.

    If chars is given and not None, remove characters in chars instead.

  static `maketrans`()

    Return a translation table usable for str.translate().

    If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters to Unicode ordinals, strings or None. Character keys will be then converted to ordinals. If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to None in the result.

  `partition`()

    Partition the string into three parts using the given separator.

    This will search for the separator in the string. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.

    If the separator is not found, returns a 3-tuple containing the original string and two empty strings.

  `pluralize`()

    Return the plural version of the word as a string.

  `replace`()

    Return a copy with all occurrences of substring old replaced by new.

    > count
    >   Maximum number of occurrences to replace. -1 (the default value) means replace all occurrences.

    If the optional argument count is given, only the first count occurrences are replaced.

  `rfind`(sub[, start[, end]]) → int

    Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

    Return -1 on failure.

  `rindex`(sub[, start[, end]]) → int

    Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

    Raises ValueError when the substring is not found.

  `rjust`()

    Return a right-justified string of length width.

    Padding is done using the specified fill character (default is a space).

  `rpartition`()

    Partition the string into three parts using the given separator.

    This will search for the separator in the string, starting at the end. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.

    If the separator is not found, returns a 3-tuple containing two empty strings and the original string.

  `rsplit`()

    Return a list of the words in the string, using sep as the delimiter string.

    > sep
    >   The delimiter according which to split the string. None (the default value) means split according to any whitespace, and discard empty strings from the result.
    > maxsplit
    >   Maximum number of splits to do. -1 (the default value) means no limit.

    Splits are done starting at the end of the string and working to the front.

  `rstrip`()

    Return a copy of the string with trailing whitespace removed.

    If chars is given and not None, remove characters in chars instead.

  `singularize`()

    Return the singular version of the word as a string.

  `spellcheck`()

    Return a list of (word, confidence) tuples of spelling corrections.

    Based on: Peter Norvig, “How to Write a Spelling Corrector” (http://norvig.com/spell-correct.html) as implemented in the pattern library.

    New in version 0.6.0: (`textblob`)

  `split`()

    Return a list of the words in the string, using sep as the delimiter string.

    sep
      The delimiter according which to split the string. None (the default value) means split according to any whitespace, and discard empty strings from the result.
    maxsplit
      Maximum number of splits to do. -1 (the default value) means no limit.
  `splitlines`()

    Return a list of the lines in the string, breaking at line boundaries.

    Line breaks are not included in the resulting list unless keepends is given and true.

  `startswith`(prefix[, start[, end]]) → bool

    Return True if S starts with the specified prefix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. prefix can also be a tuple of strings to try.

  `strip`()

    Return a copy of the string with leading and trailing whitespace remove.

    If chars is given and not None, remove characters in chars instead.

  `swapcase`()

    Convert uppercase characters to lowercase and lowercase characters to uppercase.

  `synsets`

    The list of Synset objects for this Word.

    Return type: | list of Synsets

    New in version 0.7.0: (`textblob`)

  `title`()

    Return a version of the string where each word is titlecased.

    More specifically, words start with uppercased characters and all remaining cased characters have lower case.

  `translate`(from_lang=None, to='de')

    Translate the word to another language using Google’s Translate API.

    New in version 0.5.0: (`textblob`)

  `upper`()

    Return a copy of the string converted to uppercase.

  `zfill`()

    Pad a numeric string with zeros on the left, to fill a field of the given width.

    The string is never truncated.

class `textblob_de.blob.` `WordList`(collection)

  A list-like collection of words.

  `append`(obj)

    Append an object to end. If the object is a string, appends a.

    `Word` object.

  `clear`()

    Remove all items from list.

  `copy`()

    Return a shallow copy of the list.

  `count`(strg, case_sensitive=False, *args, **kwargs)

    Get the count of a word or phrase s within this WordList.

    Parameters: | strg – The string to count. case_sensitive – A boolean, whether or not the search is case-sensitive.

  `extend`(iterable)

    Extend WordList by appending elements from `iterable`.

    If an element is a string, appends a `Word` object.

  `index`()

    Return first index of value.

    Raises ValueError if the value is not present.

  `insert`()

    Insert object before index.

  `lemmatize`()

    Return the lemma of each word in this WordList.

    Currently using NLTKPunktTokenizer() for all lemmatization tasks. This might cause slightly different tokenization results compared to the TextBlob.words property.

  `lower`()

    Return a new WordList with each word lower-cased.

  `pluralize`()

    Return the plural version of each word in this WordList.

  `pop`()

    Remove and return item at index (default last).

    Raises IndexError if list is empty or index is out of range.

  `remove`()

    Remove first occurrence of value.

    Raises ValueError if the value is not present.

  `reverse`()

    Reverse IN PLACE.

  `singularize`()

    Return the single version of each word in this WordList.

  `sort`()

    Stable sort IN PLACE.

  `upper`()

    Return a new WordList with each word upper-cased.

## Base Classes

Extensions to Abstract base classes in `textblob.base`

class `textblob_de.base.` `BaseLemmatizer`

  Abstract base class from which all Lemmatizer classes inherit. Descendant classes must implement a `lemmatize(text)` method that returns a WordList of Word object with updated lemma properties.

  New in version 0.2.3: (`textblob_de`)

  `lemmatize`(text)

    Return a list of (lemma, tag) tuples.

## Tokenizers

Various tokenizer implementations.

class `textblob_de.tokenizers.` `NLTKPunktTokenizer`

  Tokenizer included in `nltk.tokenize.punkt` package.

  This is the default tokenizer in `textblob-de`

  PROs:

  - trained model available for German
  - deals with many abbreviations and common German tokenization problems oob

  CONs:

  - not very flexible (model has to be re-trained on your own corpus)
  `itokenize`(text, *args, **kwargs)

    Return a generator that generates tokens “on-demand”.

    New in version 0.6.0.

    Return type: | generator

  `sent_tokenize`(text, **kwargs)

    NLTK’s sentence tokenizer (currently PunktSentenceTokenizer).

    Uses an unsupervised algorithm to build a model for abbreviation words, collocations, and words that start sentences, then uses that to find sentence boundaries.

  `tokenize`(text, include_punc=True, nested=False)

    Return a list of word tokens.

    Parameters: | text – string of text. include_punc – (optional) whether to include punctuation as separate tokens. Default to True. nested – (optional) whether to return tokens as nested lists of sentences. Default to False.

  `word_tokenize`(text, include_punc=True)

    The Treebank tokenizer uses regular expressions to tokenize text as in Penn Treebank.

    It assumes that the text has already been segmented into sentences, e.g. using `self.sent_tokenize()`.

    This tokenizer performs the following steps:

    - split standard contractions, e.g. `don't` -> `do n't` and `they'll` -> `they 'll`
    - treat most punctuation characters as separate tokens
    - split off commas and single quotes, when followed by whitespace
    - separate periods that appear at the end of line

    Source: NLTK’s docstring of `TreebankWordTokenizer` (accessed: 02/10/2014)

class `textblob_de.tokenizers.` `PatternTokenizer`

  Tokenizer included in `pattern.de` package.

  PROs:

  - handling of emoticons
  - flexible implementations of abbreviations
  - can be adapted very easily

  CONs:

  - ordinal numbers cause sentence breaks
  - indices of Sentence() objects cannot be computed
  `itokenize`(text, *args, **kwargs)

    Return a generator that generates tokens “on-demand”.

    New in version 0.6.0.

    Return type: | generator

  `sent_tokenize`(text, **kwargs)

    Returns a list of sentences.

    Each sentence is a space-separated string of tokens (words). Handles common cases of abbreviations (e.g., etc., …). Punctuation marks are split from other words. Periods (or ?!) mark the end of a sentence. Headings without an ending period are inferred by line breaks.

  `tokenize`(text, include_punc=True, nested=False)

    Return a list of word tokens.

    Parameters: | text – string of text. include_punc – (optional) whether to include punctuation as separate tokens. Default to True.

class `textblob_de.tokenizers.` `SentenceTokenizer`(tokenizer=None, *args, **kwargs)

  Generic sentence tokenization class, using tokenizer specified in TextBlobDE() instance.

  Enables SentenceTokenizer().itokenize generator that would be lost otherwise.

  Aim: Not to break core API of the main TextBlob library.

  Parameters: | tokenizer – (optional) A tokenizer instance. If `None`, defaults to `NLTKPunktTokenizer()`.

  `itokenize`(text, *args, **kwargs)

    Return a generator that generates tokens “on-demand”.

    New in version 0.6.0.

    Return type: | generator

  `sent_tokenize`(text, **kwargs)

    Compatibility method to tokenizers included in `textblob-de`

  `tokenize`(text, **kwargs)

    Return a list of word tokens.

    Parameters: | text – string of text. include_punc – (optional) whether to include punctuation as separate tokens. Default to True.

class `textblob_de.tokenizers.` `WordTokenizer`(tokenizer=None, *args, **kwargs)

  Generic word tokenization class, using tokenizer specified in TextBlobDE() instance.

  You can also submit the tokenizer as keyword argument: `WordTokenizer(tokenizer=NLTKPunktTokenizer())`

  Enables WordTokenizer().itokenize generator that would be lost otherwise.

  Default: NLTKPunktTokenizer().word_tokenize(text, include_punc=True)

  Aim: Not to break core API of the main TextBlob library.

  Parameters: | tokenizer – (optional) A tokenizer instance. If `None`, defaults to `NLTKPunktTokenizer()`.

  `itokenize`(text, *args, **kwargs)

    Return a generator that generates tokens “on-demand”.

    New in version 0.6.0.

    Return type: | generator

  `tokenize`(text, include_punc=True, **kwargs)

    Return a list of word tokens.

    Parameters: | text – string of text. include_punc – (optional) whether to include punctuation as separate tokens. Default to True.

  `word_tokenize`(text, include_punc=True)

    Compatibility method to tokenizers included in `textblob-de`

`textblob_de.tokenizers.` `sent_tokenize`(text, tokenizer=None)

  Convenience function for tokenizing sentences (not iterable).

  If tokenizer is not specified, the default tokenizer NLTKPunktTokenizer() is used (same behaviour as in the main TextBlob library).

  This function returns the sentences as a generator object.

`textblob_de.tokenizers.` `word_tokenize`(text, tokenizer=None, include_punc=True, *args, **kwargs)

  Convenience function for tokenizing text into words.

  NOTE: NLTK’s word tokenizer expects sentences as input, so the text will be tokenized to sentences before being tokenized to words.

  This function returns an itertools chain object (generator).

## POS Taggers

Default taggers for German.

    >>> from textblob_de.taggers import PatternTagger

or

    >>> from textblob_de import PatternTagger

class `textblob_de.taggers.` `PatternTagger`(tokenizer=None, include_punc=False, encoding='utf-8', tagset=None)

  Tagger that uses the implementation in Tom de Smedt’s pattern library (http://www.clips.ua.ac.be/pattern).

  Parameters: | tokenizer – (optional) A tokenizer instance. If `None`, defaults to `PatternTokenizer()`. include_punc – (optional) whether to include punctuation as separate tokens. Default to `False`. encoding – (optional) Input string encoding. (Default `utf-8`) tagset – (optional) Penn Treebank II (default) or (‘penn’|’universal’|’stts’).

  `tag`(sentence, tokenize=True)

    Tag a string sentence.

    Parameters: | or list sentence (str) – A string or a list of sentence strings. tokenize – (optional) If `False` string has to be tokenized before (space separated string).

## Noun Phrase Extractors

Various noun phrase extractor implementations.

# `PatternParserNPExtractor()`.

class `textblob_de.np_extractors.` `PatternParserNPExtractor`(tokenizer=None)

  Extract noun phrases (NP) from PatternParser() output.

  Very naïve and resource hungry approach:

  - get parser output
  - try to correct as many obvious parser errors as you can (e.g. eliminate wrongly tagged verbs)
  - filter insignificant words

  Parameters: | tokenizer – (optional) A tokenizer instance. If `None`, defaults to `PatternTokenizer()`.

  `extract`(text)

    Return a list of noun phrases (strings) for a body of text.

    Parameters: | text (str) – A string.

## Sentiment Analyzers

German sentiment analysis implementations.

Main resource for `de-sentiment.xml`:

- German Polarity Lexicon
- See xml comment section in `de-sentiment.xml` for details

class `textblob_de.sentiments.` `PatternAnalyzer`(tokenizer=None, lemmatizer=None, lemmatize=True)

  Sentiment analyzer that uses the same implementation as the pattern library. Returns results as a tuple of the form:

  `(polarity, subjectivity)`

  `RETURN_TYPE`

    Return type declaration

    alias of `Sentiment`

  `analyze`(text)

    Return the sentiment as a tuple of the form: `(polarity, subjectivity)`

    Parameters: | text (str) – A string.

  `kind` = 'co'

    Enhancement Issue #2 adapted from ‘textblob.en.sentiments.py’

class `textblob_de.sentiments.` `Sentiment`(path='', language=None, synset=None, confidence=None, **kwargs)
  `annotate`(word, pos=None, polarity=0.0, subjectivity=0.0, intensity=1.0, label=None)

    Annotates the given word with polarity, subjectivity and intensity scores, and optionally a semantic label (e.g., MOOD for emoticons, IRONY for “(!)”).

  `assessments`(words=[], negation=True)

    Returns a list of (chunk, polarity, subjectivity, label)-tuples for the given list of words: where chunk is a list of successive words: a known word optionally preceded by a modifier (“very good”) or a negation (“not good”).

  `clear`() → None. Remove all items from D.
  `copy`() → a shallow copy of D
  `fromkeys`()

    Create a new dictionary with keys from iterable and values set to value.

  `get`(*args, **kwargs)

    Return the value for key if key is in the dictionary, else default.

  `items`() → a set-like object providing a view on D's items
  `keys`() → a set-like object providing a view on D's keys
  `load`(path=None)

    Loads the XML-file (with sentiment annotations) from the given path. By default, Sentiment.path is lazily loaded.

  `pop`(k[, d]) → v, remove specified key and return the corresponding value.

    If key is not found, d is returned if given, otherwise KeyError is raised

  `popitem`() → (k, v), remove and return some (key, value) pair as a

    2-tuple; but raise KeyError if D is empty.

  `setdefault`(*args)

    Insert key with a value of default if key is not in the dictionary.

    Return the value for key if key is in the dictionary, else default.

  `synset`(id, pos='JJ')

    Returns a (polarity, subjectivity)-tuple for the given synset id. For example, the adjective “horrible” has id 193480 in WordNet: Sentiment.synset(193480, pos=”JJ”) => (-0.6, 1.0, 1.0).

  `update`([E, ]**F) → None. Update D from dict/iterable E and F.

    If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k]

  `values`() → an object providing a view on D's values

## Parsers

Default parsers for German.

    >>> from textblob_de.parsers import PatternParser

or

    >>> from textblob_de import PatternParser

class `textblob_de.parsers.` `PatternParser`(tokenizer=None, tokenize=True, pprint=False, tags=True, chunks=True, relations=False, lemmata=False, encoding='utf-8', tagset=None)

  Parser that uses the implementation in Tom de Smedt’s pattern library. http://www.clips.ua.ac.be/pages/pattern-de#parser

  Parameters: | tokenizer – (optional) A tokenizer instance. If `None`, defaults to `PatternTokenizer()`. tokenize – (optional) Split punctuation marks from words? (Default `True`) pprint – (optional) Use `pattern`’s `pprint` function to display parse trees (Default `False`) tags – (optional) Parse part-of-speech tags? (NN, JJ, …) (Default `True`) chunks – (optional) Parse chunks? (NP, VP, PNP, …) (Default `True`) relations – (optional) Parse chunk relations? (-SBJ, -OBJ, …) (Default `False`) lemmata – (optional) Parse lemmata? (schönes => schön) (Default `False`) encoding – (optional) Input string encoding. (Default `utf-8`) tagset – (optional) Penn Treebank II (default) or (‘penn’|’universal’|’stts’).

  `parse`(text)

    Parses the text.

    `pattern.de.parse(**kwargs)` can be passed to the parser instance and are documented in the main docstring of `PatternParser()`.

    Parameters: | text (str) – A string.

  `parsetree`(text)

    Returns a parsed `pattern` Text object from the given string.

## Classifiers (from TextBlob main package)

Various classifier implementations. Also includes basic feature extractor methods.

Example Usage:

    >>> from textblob import TextBlob
    >>> from textblob.classifiers import NaiveBayesClassifier
    >>> train = [
    ...     ('I love this sandwich.', 'pos'),
    ...     ('This is an amazing place!', 'pos'),
    ...     ('I feel very good about these beers.', 'pos'),
    ...     ('I do not like this restaurant', 'neg'),
    ...     ('I am tired of this stuff.', 'neg'),
    ...     ("I can't deal with this", 'neg'),
    ...     ("My boss is horrible.", "neg")
    ... ]
    >>> cl = NaiveBayesClassifier(train)
    >>> cl.classify("I feel amazing!")
    'pos'
    >>> blob = TextBlob("The beer is good. But the hangover is horrible.", classifier=cl)
    >>> for s in blob.sentences:
    ...     print(s)
    ...     print(s.classify())
    ...
    The beer is good.
    pos
    But the hangover is horrible.
    neg

New in version 0.6.0.

class `textblob.classifiers.` `BaseClassifier`(train_set, feature_extractor=<function basic_extractor>, format=None, **kwargs)

  Abstract classifier class from which all classifers inherit. At a minimum, descendant classes must implement a `classify` method and have a `classifier` property.

  Parameters: | train_set – The training set, either a list of tuples of the form `(text, classification)` or a file-like object. `text` may be either a string or an iterable. feature_extractor (callable) – A feature extractor function that takes one or two arguments: `document` and `train_set`. format (str) – If `train_set` is a filename, the file format, e.g. `"csv"` or `"json"`. If `None`, will attempt to detect the file format. kwargs – Additional keyword arguments are passed to the constructor of the `Format` class used to read the data. Only applies when a file-like object is passed as `train_set`.

  New in version 0.6.0.

  `classifier`

    The classifier object.

  `classify`(text)

    Classifies a string of text.

  `extract_features`(text)

    Extracts features from a body of text.

    Return type: | dictionary of features

  `labels`()

    Returns an iterable containing the possible labels.

  `train`(labeled_featureset)

    Trains the classifier.

class `textblob.classifiers.` `DecisionTreeClassifier`(train_set, feature_extractor=<function basic_extractor>, format=None, **kwargs)

  A classifier based on the decision tree algorithm, as implemented in NLTK.

  Parameters: | train_set – The training set, either a list of tuples of the form `(text, classification)` or a filename. `text` may be either a string or an iterable. feature_extractor – A feature extractor function that takes one or two arguments: `document` and `train_set`. format – If `train_set` is a filename, the file format, e.g. `"csv"` or `"json"`. If `None`, will attempt to detect the file format.

  New in version 0.6.2.

  `accuracy`(test_set, format=None)

    Compute the accuracy on a test set.

    Parameters: | test_set – A list of tuples of the form `(text, label)`, or a file pointer. format – If `test_set` is a filename, the file format, e.g. `"csv"` or `"json"`. If `None`, will attempt to detect the file format.

  `classifier`

    The classifier.

  `classify`(text)

    Classifies the text.

    Parameters: | text (str) – A string of text.

  `extract_features`(text)

    Extracts features from a body of text.

    Return type: | dictionary of features

  `labels`()

    Return an iterable of possible labels.

  `nltk_class`

    alias of `nltk.classify.decisiontree.DecisionTreeClassifier`

  `pprint`(*args, **kwargs)

    Return a string containing a pretty-printed version of this decision tree. Each line in the string corresponds to a single decision tree node or leaf, and indentation is used to display the structure of the tree.

    Return type: | str

  `pretty_format`(*args, **kwargs)

    Return a string containing a pretty-printed version of this decision tree. Each line in the string corresponds to a single decision tree node or leaf, and indentation is used to display the structure of the tree.

    Return type: | str

  `pseudocode`(*args, **kwargs)

    Return a string representation of this decision tree that expresses the decisions it makes as a nested set of pseudocode if statements.

    Return type: | str

  `train`(*args, **kwargs)

    Train the classifier with a labeled feature set and return the classifier. Takes the same arguments as the wrapped NLTK class. This method is implicitly called when calling `classify` or `accuracy` methods and is included only to allow passing in arguments to the `train` method of the wrapped NLTK class.

    New in version 0.6.2.

    Return type: | A classifier

  `update`(new_data, *args, **kwargs)

    Update the classifier with new training data and re-trains the classifier.

    Parameters: | new_data – New data as a list of tuples of the form `(text, label)`.

class `textblob.classifiers.` `MaxEntClassifier`(train_set, feature_extractor=<function basic_extractor>, format=None, **kwargs)

  A maximum entropy classifier (also known as a “conditional exponential classifier”). This classifier is parameterized by a set of “weights”, which are used to combine the joint-features that are generated from a featureset by an “encoding”. In particular, the encoding maps each `(featureset, label)` pair to a vector. The probability of each label is then computed using the following equation:

                                dotprod(weights, encode(fs,label))
      prob(fs|label) = ---------------------------------------------------
                       sum(dotprod(weights, encode(fs,l)) for l in labels)

  Where `dotprod` is the dot product:

      dotprod(a,b) = sum(x*y for (x,y) in zip(a,b))

  `accuracy`(test_set, format=None)

    Compute the accuracy on a test set.

    Parameters: | test_set – A list of tuples of the form `(text, label)`, or a file pointer. format – If `test_set` is a filename, the file format, e.g. `"csv"` or `"json"`. If `None`, will attempt to detect the file format.

  `classifier`

    The classifier.

  `classify`(text)

    Classifies the text.

    Parameters: | text (str) – A string of text.

  `extract_features`(text)

    Extracts features from a body of text.

    Return type: | dictionary of features

  `labels`()

    Return an iterable of possible labels.

  `nltk_class`

    alias of `nltk.classify.maxent.MaxentClassifier`

  `prob_classify`(text)

    Return the label probability distribution for classifying a string of text.

    Example:

        >>> classifier = MaxEntClassifier(train_data)
        >>> prob_dist = classifier.prob_classify("I feel happy this morning.")
        >>> prob_dist.max()
        'positive'
        >>> prob_dist.prob("positive")
        0.7

    Return type: | nltk.probability.DictionaryProbDist

  `train`(*args, **kwargs)

    Train the classifier with a labeled feature set and return the classifier. Takes the same arguments as the wrapped NLTK class. This method is implicitly called when calling `classify` or `accuracy` methods and is included only to allow passing in arguments to the `train` method of the wrapped NLTK class.

    New in version 0.6.2.

    Return type: | A classifier

  `update`(new_data, *args, **kwargs)

    Update the classifier with new training data and re-trains the classifier.

    Parameters: | new_data – New data as a list of tuples of the form `(text, label)`.

class `textblob.classifiers.` `NLTKClassifier`(train_set, feature_extractor=<function basic_extractor>, format=None, **kwargs)

  An abstract class that wraps around the nltk.classify module.

  Expects that descendant classes include a class variable `nltk_class` which is the class in the nltk.classify module to be wrapped.

  Example:

      class MyClassifier(NLTKClassifier):
          nltk_class = nltk.classify.svm.SvmClassifier

  `accuracy`(test_set, format=None)

    Compute the accuracy on a test set.

    Parameters: | test_set – A list of tuples of the form `(text, label)`, or a file pointer. format – If `test_set` is a filename, the file format, e.g. `"csv"` or `"json"`. If `None`, will attempt to detect the file format.

  `classifier`

    The classifier.

  `classify`(text)

    Classifies the text.

    Parameters: | text (str) – A string of text.

  `extract_features`(text)

    Extracts features from a body of text.

    Return type: | dictionary of features

  `labels`()

    Return an iterable of possible labels.

  `nltk_class` = None

    The NLTK class to be wrapped. Must be a class within nltk.classify

  `train`(*args, **kwargs)

    Train the classifier with a labeled feature set and return the classifier. Takes the same arguments as the wrapped NLTK class. This method is implicitly called when calling `classify` or `accuracy` methods and is included only to allow passing in arguments to the `train` method of the wrapped NLTK class.

    New in version 0.6.2.

    Return type: | A classifier

  `update`(new_data, *args, **kwargs)

    Update the classifier with new training data and re-trains the classifier.

    Parameters: | new_data – New data as a list of tuples of the form `(text, label)`.

class `textblob.classifiers.` `NaiveBayesClassifier`(train_set, feature_extractor=<function basic_extractor>, format=None, **kwargs)

  A classifier based on the Naive Bayes algorithm, as implemented in NLTK.

  Parameters: | train_set – The training set, either a list of tuples of the form `(text, classification)` or a filename. `text` may be either a string or an iterable. feature_extractor – A feature extractor function that takes one or two arguments: `document` and `train_set`. format – If `train_set` is a filename, the file format, e.g. `"csv"` or `"json"`. If `None`, will attempt to detect the file format.

  New in version 0.6.0.

  `accuracy`(test_set, format=None)

    Compute the accuracy on a test set.

    Parameters: | test_set – A list of tuples of the form `(text, label)`, or a file pointer. format – If `test_set` is a filename, the file format, e.g. `"csv"` or `"json"`. If `None`, will attempt to detect the file format.

  `classifier`

    The classifier.

  `classify`(text)

    Classifies the text.

    Parameters: | text (str) – A string of text.

  `extract_features`(text)

    Extracts features from a body of text.

    Return type: | dictionary of features

  `informative_features`(*args, **kwargs)

    Return the most informative features as a list of tuples of the form `(feature_name, feature_value)`.

    Return type: | list

  `labels`()

    Return an iterable of possible labels.

  `nltk_class`

    alias of `nltk.classify.naivebayes.NaiveBayesClassifier`

  `prob_classify`(text)

    Return the label probability distribution for classifying a string of text.

    Example:

        >>> classifier = NaiveBayesClassifier(train_data)
        >>> prob_dist = classifier.prob_classify("I feel happy this morning.")
        >>> prob_dist.max()
        'positive'
        >>> prob_dist.prob("positive")
        0.7

    Return type: | nltk.probability.DictionaryProbDist

  `show_informative_features`(*args, **kwargs)

    Displays a listing of the most informative features for this classifier.

    Return type: | None

  `train`(*args, **kwargs)

    Train the classifier with a labeled feature set and return the classifier. Takes the same arguments as the wrapped NLTK class. This method is implicitly called when calling `classify` or `accuracy` methods and is included only to allow passing in arguments to the `train` method of the wrapped NLTK class.

    New in version 0.6.2.

    Return type: | A classifier

  `update`(new_data, *args, **kwargs)

    Update the classifier with new training data and re-trains the classifier.

    Parameters: | new_data – New data as a list of tuples of the form `(text, label)`.

class `textblob.classifiers.` `PositiveNaiveBayesClassifier`(positive_set, unlabeled_set, feature_extractor=<function contains_extractor>, positive_prob_prior=0.5, **kwargs)

  A variant of the Naive Bayes Classifier that performs binary classification with partially-labeled training sets, i.e. when only one class is labeled and the other is not. Assuming a prior distribution on the two labels, uses the unlabeled set to estimate the frequencies of the features.

  Example usage:

      >>> from text.classifiers import PositiveNaiveBayesClassifier
      >>> sports_sentences = ['The team dominated the game',
      ...                   'They lost the ball',
      ...                   'The game was intense',
      ...                   'The goalkeeper catched the ball',
      ...                   'The other team controlled the ball']
      >>> various_sentences = ['The President did not comment',
      ...                        'I lost the keys',
      ...                        'The team won the game',
      ...                        'Sara has two kids',
      ...                        'The ball went off the court',
      ...                        'They had the ball for the whole game',
      ...                        'The show is over']
      >>> classifier = PositiveNaiveBayesClassifier(positive_set=sports_sentences,
      ...                                           unlabeled_set=various_sentences)
      >>> classifier.classify("My team lost the game")
      True
      >>> classifier.classify("And now for something completely different.")
      False

  Parameters: | positive_set – A collection of strings that have the positive label. unlabeled_set – A collection of unlabeled strings. feature_extractor – A feature extractor function. positive_prob_prior – A prior estimate of the probability of the label `True`.

  New in version 0.7.0.

  `accuracy`(test_set, format=None)

    Compute the accuracy on a test set.

    Parameters: | test_set – A list of tuples of the form `(text, label)`, or a file pointer. format – If `test_set` is a filename, the file format, e.g. `"csv"` or `"json"`. If `None`, will attempt to detect the file format.

  `classifier`

    The classifier.

  `classify`(text)

    Classifies the text.

    Parameters: | text (str) – A string of text.

  `extract_features`(text)

    Extracts features from a body of text.

    Return type: | dictionary of features

  `labels`()

    Return an iterable of possible labels.

  `nltk_class`

    alias of `nltk.classify.positivenaivebayes.PositiveNaiveBayesClassifier`

  `train`(*args, **kwargs)

    Train the classifier with a labeled and unlabeled feature sets and return the classifier. Takes the same arguments as the wrapped NLTK class. This method is implicitly called when calling `classify` or `accuracy` methods and is included only to allow passing in arguments to the `train` method of the wrapped NLTK class.

    Return type: | A classifier

  `update`(new_positive_data=None, new_unlabeled_data=None, positive_prob_prior=0.5, *args, **kwargs)

    Update the classifier with new data and re-trains the classifier.

    Parameters: | new_positive_data – List of new, labeled strings. new_unlabeled_data – List of new, unlabeled strings.

`textblob.classifiers.` `basic_extractor`(document, train_set)

  A basic document feature extractor that returns a dict indicating what words in `train_set` are contained in `document`.

  Parameters: | document – The text to extract features from. Can be a string or an iterable. train_set (list) – Training data set, a list of tuples of the form `(words, label)` OR an iterable of strings.

`textblob.classifiers.` `contains_extractor`(document)

  A basic document feature extractor that returns a dict of words that the document contains.

## Blobber

class `textblob_de.blob.` `BlobberDE`(tokenizer=None, pos_tagger=None, np_extractor=None, analyzer=None, parser=None, classifier=None)

  A factory for TextBlobs that all share the same tagger, tokenizer, parser, classifier, and np_extractor.

  Usage:

      >>> from textblob_de import BlobberDE
      >>> from textblob_de.taggers import PatternTagger
      >>> from textblob.tokenizers import PatternTokenizer
      >>> tb = Blobber(pos_tagger=PatternTagger(), tokenizer=PatternTokenizer())
      >>> blob1 = tb("Das ist ein Blob.")
      >>> blob2 = tb("Dieser Blob benutzt die selben Tagger und Tokenizer.")
      >>> blob1.pos_tagger is blob2.pos_tagger
      True

  Parameters: | text (str) – A string. tokenizer – (optional) A tokenizer instance. If `None`, defaults to `NLTKPunktTokenizer()`. np_extractor – (optional) An NPExtractor instance. If `None`, defaults to `PatternParserNPExtractor()`. pos_tagger – (optional) A Tagger instance. If `None`, defaults to `PatternTagger`. analyzer – (optional) A sentiment analyzer. If `None`, defaults to `PatternAnalyzer`. classifier – (optional) A classifier.

  New in version 0.4.0: (`textblob`)

  `__call__`(text)

    Return a new TextBlob object with this Blobber’s `np_extractor`, `pos_tagger`, `tokenizer`, `analyzer`, and `classifier`.

    Returns: | A new `TextBlob`.

  `__init__`(tokenizer=None, pos_tagger=None, np_extractor=None, analyzer=None, parser=None, classifier=None)

    Initialize self. See help(type(self)) for accurate signature.

  `__repr__`()

    Return repr(self).

  `__str__`()

    Return repr(self).

## File Formats (from TextBlob main package)

File formats for training and testing data.

Includes a registry of valid file formats. New file formats can be added to the registry like so:

    from textblob import formats

    class PipeDelimitedFormat(formats.DelimitedFormat):
        delimiter = '|'

    formats.register('psv', PipeDelimitedFormat)

Once a format has been registered, classifiers will be able to read data files with that format.

    from textblob.classifiers import NaiveBayesAnalyzer

    with open('training_data.psv', 'r') as fp:
        cl = NaiveBayesAnalyzer(fp, format='psv')

class `textblob.formats.` `BaseFormat`(fp, **kwargs)

  Interface for format classes. Individual formats can decide on the composition and meaning of `**kwargs`.

  Parameters: | fp (File) – A file-like object.

  Changed in version 0.9.0: Constructor receives a file pointer rather than a file path.

  classmethod `detect`(stream)

    Detect the file format given a filename. Return True if a stream is this file format.

    Changed in version 0.9.0: Changed from a static method to a class method.

  `to_iterable`()

    Return an iterable object from the data.

class `textblob.formats.` `CSV`(fp, **kwargs)

  CSV format. Assumes each row is of the form `text,label`.

      Today is a good day,pos
      I hate this car.,pos

  classmethod `detect`(stream)

    Return True if stream is valid.

  `to_iterable`()

    Return an iterable object from the data.

class `textblob.formats.` `DelimitedFormat`(fp, **kwargs)

  A general character-delimited format.

  classmethod `detect`(stream)

    Return True if stream is valid.

  `to_iterable`()

    Return an iterable object from the data.

class `textblob.formats.` `JSON`(fp, **kwargs)

  JSON format.

  Assumes that JSON is formatted as an array of objects with `text` and `label` properties.

      [
          {"text": "Today is a good day.", "label": "pos"},
          {"text": "I hate this car.", "label": "neg"}
      ]

  classmethod `detect`(stream)

    Return True if stream is valid JSON.

  `to_iterable`()

    Return an iterable object from the JSON data.

class `textblob.formats.` `TSV`(fp, **kwargs)

  TSV format. Assumes each row is of the form `text label`.

  classmethod `detect`(stream)

    Return True if stream is valid.

  `to_iterable`()

    Return an iterable object from the data.

`textblob.formats.` `detect`(fp, max_read=1024)

  Attempt to detect a file’s format, trying each of the supported formats. Return the format class that was detected. If no format is detected, return `None`.

`textblob.formats.` `get_registry`()

  Return a dictionary of registered formats.

`textblob.formats.` `register`(name, format_class)

  Register a new format.

  Parameters: | name (str) – The name that will be used to refer to the format, e.g. ‘csv’ format_class (type) – The format class to register.

## Exceptions (from TextBlob main package)

`textblob.exceptions.` `MissingCorpusException`

  alias of `textblob.exceptions.MissingCorpusError`