textflint.input_layer.component.sample.sample

Base Sample Abstract Class

class textflint.input_layer.component.sample.sample.Sample(data, origin=None, sample_id=None)[source]

Bases: abc.ABC

Base Sample class to hold the necessary info and provide atomic operations

text_processor = <textflint.common.preprocess.en_processor.EnProcessor object>
__init__(data, origin=None, sample_id=None)[source]
Parameters
  • data (dict) – The dict obj that contains data info.

  • origin (sample) – original sample obj.

  • sample_id (int) – sampleindex

get_value(field)[source]

Get field value by field_str.

Parameters

field (str) – field name

Returns

field value

get_words(field)[source]

Get tokenized words of given textfield

Parameters

field (str) – field name

Returns

tokenized words

get_text(field)[source]

Get text string of given textfield

Parameters

field (str) – field name

Return string

text

get_mask(field)[source]

Get word masks of given textfield

Parameters

field (str) – field name

Returns

list of mask values

get_sentences(field)[source]

Get split sentences of given textfield

Parameters

field (str) – field name

Returns

list of sentences

get_pos(field)[source]

Get text field pos tags. :param str field: field name :return: pos tag list

get_ner(field)[source]

Get text field ner tags

Parameters

field (str) – field name

Returns

ner tag list

replace_fields(fields, field_values, field_masks=None)[source]

Fully replace multi fields at the same time and return new sample. Notice: Not suggest use this API as it will set mask values of TextField to MODIFIED_MASK.

Parameters
  • fields (list) – field str list

  • field_values (list) – field value list

  • field_masks (list) – indicate mask values, useful for printable text

Returns

Modified Sample

replace_field(field, field_value, field_mask=None)[source]

Fully replace single field and return new sample. Notice: Not suggest use this API as it will set mask values of TextField to MODIFIED_MASK.

Parameters
  • field (str) – field str

  • field_value – field_type

  • field_mask (list) – indicate mask value of field

Returns

Modified Sample

replace_field_at_indices(field, indices, items)[source]

Replace items of multi given scopes of field value at the same time. Stay away from the complex function !!!

Be careful of your input list shape.

Parameters
  • field (str) – field name

  • of int|list|slice indices (list) –

    each index can be int indicate replace single item or their list

    like [1, 2, 3],

    can be list like (0,3) indicate replace items from

    0 to 3(not included),

    can be slice which would be convert to list.

  • items

Returns

Modified Sample

replace_field_at_index(field, index, items)[source]

Replace items of given scope of field value.

Be careful of your input list shape.

Parameters
  • field (str) – field name

  • index (int|list|slice) –

    can be int indicate replace single item or list like [1, 2, 3], can be list like (0,3) indicate replace items

    from 0 to 3(not included),

    can be slice which would be convert to list.

  • items (str|list) – shape: indices_num, correspond to field_sub_items

Returns

Modified Sample

unequal_replace_field_at_indices(field, indices, rep_items)[source]

Replace scope items of field value with rep_items which may not equal with scope.

Parameters
  • field – field str

  • indices – list of int/tupe/list

  • rep_items – list

Returns

Modified Sample

delete_field_at_indices(field, indices)[source]

Delete items of given scopes of field value.

Parameters
  • field (str) – field name

  • of int|list|slice indices (list) –

    shape:indices_num each index can be int indicate delete single item or their list

    like [1, 2, 3],

    can be list like (0,3) indicate replace items

    from 0 to 3(not included),

    can be slice which would be convert to list.

Returns

Modified Sample

delete_field_at_index(field, index)[source]

Delete items of given scopes of field value.

Parameters
  • field (str) – field value

  • index (int|list|slice) –

    can be int indicate delete single item or their list like [1, 2, 3], can be list like (0,3) indicate replace items

    from 0 to 3(not included),

    can be slice which would be convert to list.

Returns

Modified Sample

insert_field_before_indices(field, indices, items)[source]

Insert items of multi given scopes before indices of field value at the same time.

Stay away from the complex function !!! Be careful of your input list shape.

Parameters
  • field (str) – field name

  • indices – list of int, shape:indices_num, list like [1, 2, 3]

  • items – list of str/list, shape: indices_num, correspond to indices

Returns

Modified Sample

insert_field_before_index(field, index, items)[source]

Insert items of multi given scope before index of field value.

Parameters
  • field (str) – field name

  • index (int) – indicate which index to insert items

  • items (str|list) – items to insert

Returns

Modified Sample

insert_field_after_indices(field, indices, items)[source]

Insert items of multi given scopes after indices of field value at the same time.

Stay away from the complex function !!! Be careful of your input list shape.

Parameters
  • field (str) – field name

  • indices – list of int, shape:indices_num, like [1, 2, 3]

  • items – list of str/list shape: indices_num, correspond to indices

Returns

Modified Sample

insert_field_after_index(field, index, items)[source]

Insert items of multi given scope after index of field value

Parameters
  • field (str) – field name

  • index (int) – indicate where to apply insert

  • items (str|list) – shape: indices_num, correspond to field_sub_items

Returns

Modified Sample

swap_field_at_index(field, first_index, second_index)[source]

Swap items between first_index and second_index of field value.

Parameters
  • field (str) – field name

  • first_index (int) –

  • second_index (int) –

Returns

Modified Sample

abstract check_data(data)[source]

Check rare data format

Parameters

data – rare data input

Returns

abstract load(data)[source]

Parse data into sample field value.

Parameters

data – rare data input

abstract dump()[source]

Convert sample info to input data json format.

Returns

dict object.

classmethod clone(original_sample)[source]

Deep copy self to a new sample

Parameters

original_sample – sample to be copied

Returns

Sample instance

property is_origin

Return whether the sample is original Sample.

class textflint.input_layer.component.sample.sample.ABC[source]

Bases: object

Helper class that provides a standard way to create an ABC using inheritance.

class textflint.input_layer.component.sample.sample.EnProcessor(*args, **kwargs)[source]

Bases: object

Text Processor class implement NER, POS tag, lexical tree parsing. EnProcessor is designed by single instance mode.

sentence_tokenize(text)[source]

Split text to sentences.

Parameters

text (str) – text string

Returns

list[str]

tokenize_one_sent(text, split_by_space=False)[source]

Tokenize one sentence.

Parameters
  • text (str) –

  • split_by_space (bool) – whether tokenize sentence by split space

Returns

tokens

tokenize(text, is_one_sent=False, split_by_space=False)[source]

Split a text into tokens (words, morphemes we can separate such as “n’t”, and punctuation).

Parameters
  • text (str) –

  • is_one_sent (bool) –

  • split_by_space (bool) –

Returns

list of tokens

static inverse_tokenize(tokens)[source]

Convert tokens to sentence.

Untokenizing a text undoes the tokenizing operation, restoring punctuation and spaces to the places that people expect them to be. Ideally, untokenize(tokenize(text)) should be identical to text, except for line breaks.

Watch out! Default punctuation add to the word before its index, it may raise inconsistency bug.

Parameters

tokens (list[str]r) – target token list

Returns

str

get_pos(sentence)[source]

POS tagging function.

Example:

EnProcessor().get_pos(
    'All things in their being are good for something.'
)

>> [('All', 'DT'),
    ('things', 'NNS'),
    ('in', 'IN'),
    ('their', 'PRP$'),
    ('being', 'VBG'),
    ('are', 'VBP'),
    ('good', 'JJ'),
    ('for', 'IN'),
    ('something', 'NN'),
    ('.', '.')]
Parameters

sentence (str|list) – A sentence which needs to be tokenized.

Returns

Tokenized tokens with their POS tags.

get_ner(sentence, return_char_idx=True)[source]

NER function. This method uses implemented based on spacy model.

Example:

EnProcessor().get_ner(
    'Lionel Messi is a football player from Argentina.'
)

if return_word_index is False
>>[('Lionel Messi', 0, 12, 'PERSON'),
   ('Argentina', 39, 48, 'LOCATION')]

if return_word_index is True
>>[('Lionel Messi', 0, 2, 'PERSON'),
   ('Argentina', 7, 8, 'LOCATION')]
Parameters
  • sentence (str|list) – text string or token list

  • return_char_idx (bool) – if set True, return character start to end index, else return char start to end index.

Returns

A list of tuples, (entity, start, end, label)

get_parser(sentence)[source]

Lexical tree parsing function based on NLTK toolkit.

Example:

EnProcessor().get_parser('Messi is a football player.')

>>'(ROOT\n  (S\n    (NP (NNP Messi))\n    (VP (VBZ is) (NP (DT a)
(NN football) (NN player)))\n    (. .)))'
Parameters

sentence (str|list) – A sentence needs to be parsed.

:return:The result tree of lexicalized parser in string format.

get_dep_parser(sentence, is_one_sent=True, split_by_space=False)[source]

Dependency parsing based on spacy model.

Example:

EnProcessor().get_dep_parser(
'The quick brown fox jumps over the lazy dog.'
)

>>
    The     DT      4       det
    quick   JJ      4       amod
    brown   JJ      4       amod
    fox     NN      5       nsubj
    jumps   VBZ     0       root
    over    IN      9       case
    the     DT      9       det
    lazy    JJ      9       amod
    dog     NN      5       obl
Parameters
  • sentence (str|list) – input text string

  • is_one_sent (bool) – whether do sentence tokenzie

  • split_by_space (bool) – whether tokenize sentence by split with ” “

Returns

dp tags.

get_lemmas(token_and_pos)[source]

Lemmatize function. This method uses nltk.WordNetLemmatier to lemmatize tokens.

Parameters

token_and_pos (list) – (token, POS).

Returns

A lemma or a list of lemmas depends on your input.

get_all_lemmas(pos)[source]

Lemmatize function for all words in WordNet.

Parameters

pos – POS tag pr a list of POS tag.

Returns

A list of lemmas that have the given pos tag.

get_delemmas(lemma_and_pos)[source]

Delemmatize function.

This method uses a pre-processed dict which maps (lemma, pos) to original token for delemmatizing.

Parameters

lemma_and_pos (tuple|list) – A tuple or a list of (lemma, POS).

Returns

A word or a list of words, each word represents the specific form of input lemma.

get_synsets(tokens_and_pos, lang='eng')[source]

Get synsets from WordNet.

Parameters
  • tokens_and_pos (list) – A list of tuples, (token, POS).

  • lang (str) – language name

Returns

A list of str, represents the sense of each input token.

get_antonyms(tokens_and_pos, lang='eng')[source]

Get antonyms from WordNet.

This method uses NTLK WordNet to generate antonyms, and uses “lesk” algorithm which is proposed by Michael E. Lesk in 1986, to screen the sense out.

Parameters
  • tokens_and_pos (list) – A list of tuples, (token, POS).

  • lang (str) – language name.

Returns

A list of str, represents the sense of each input token.

filter_candidates_by_pos(token_and_pos, candidates)[source]

Filter synonyms not contain the same pos tag with given token.

Parameters
  • token_and_pos (list|tuple) – (token, pos)

  • candidates (list) – strings to verify

Returns

filtered candidates list.

feature_extract(sent)[source]

Generate linguistic tags for tokens.

Parameters

sent (str) – input sentence

Returns

list of dict

class textflint.input_layer.component.sample.sample.ListField(field_value, **kwargs)[source]

Bases: textflint.input_layer.component.field.field.Field

A helper class that represents input list values that to be modified.

Operations which modify field_value would generate new Field instance.

__init__(field_value, **kwargs)[source]
Parameters

field_value ([str]) – The list that ListField represents.

replace_at_indices(indices, new_items)[source]

Replace items at indices.

Notice: just support isometric replace.

Parameters
  • indices (list[int|list|slice]) – each index can be int indicate replace single item or their list like [1, 2, 3]. each index can be list like (0,3) indicate replace items from 0 to 3(not included) or their list like [(0, 3), (5,6)] each index can be slice which would be convert to list.

  • new_items (list) – items corresponding indices.

Returns

new field object.

replace_at_index(index, new_items)[source]

Replace item at index.

Parameters
  • index (int|list|slice) –

    can be int indicate replace single item or their list like [1, 2, 3] can be list like (0,3) indicate replace items from 0

    to 3(not included) or their list like [(0, 3), (5,6)]

    can be slice which would be convert to list.

  • new_items (list) – items corresponding index.

Returns

new field object.

delete_at_indices(indices)[source]

Delete items at indices.

Parameters

indices (list[int|list|slice]) – each index can be int indicate delete single item or their list like [1, 2, 3]. each index can be list like (0,3) indicate replace items from 0 to 3(not included) or their list like [(0, 3), (5,6)] each index can be slice which would be convert to list.

Returns

new field object.

delete_at_index(index)[source]

Delete item at index.

Parameters

index (int|list|slice) –

can be int indicate delete single item or their list like [1, 2, 3] can be list like (0,3) indicate replace items from 0

to 3(not included) or their list like [(0, 3), (5,6)]

can be slice which would be convert to list.

Returns

new field object.

insert_before_indices(indices, new_items)[source]

Insert items before indices.

Parameters
  • indices (list[int|list|slice]) – each index can be int indicate insert single item or their list like [1, 2, 3]. each index can be list like (0,3) indicate replace items from 0 to 3(not included) or their list like [(0, 3), (5,6)] each index can be slice which would be convert to list.

  • new_items (list) – items corresponding indices.

Returns

new field object.

insert_before_index(index, new_items)[source]

Insert items before index.

Parameters
  • index (int|list|slice) –

    can be int indicate insert single item or their list like [1, 2, 3] can be list like (0,3) indicate replace items from 0

    to 3(not included) or their list like [(0, 3), (5,6)]

    can be slice which would be convert to list.

  • new_items (list) – items corresponding index.

Returns

new field object.

insert_after_indices(indices, new_items)[source]

Insert item after index.

Parameters
  • indices (list[int|list|slice]) – each index can be int indicate insert single item or their list like [1, 2, 3]. each index can be list like (0,3) indicate replace items from 0 to 3(not included) or their list like [(0, 3), (5,6)] each index can be slice which would be convert to list.

  • new_items (list) – items corresponding indices.

Returns

new field object.

insert_after_index(index, new_items)[source]

Insert item after index.

Parameters
  • index (int|list|slice) –

    can be int indicate insert single item or their list like [1, 2, 3] can be list like (0,3) indicate replace items from 0

    to 3(not included) or their list like [(0, 3), (5,6)]

    can be slice which would be convert to list.

  • new_items (list) – items corresponding index

Returns

new field object.

swap_at_index(first_index, second_index)[source]

Swap item between first_index and second_index.

Parameters
  • first_index (int) – index of first item

  • second_index (int) – index of second item

Returns

new field object.

class textflint.input_layer.component.sample.sample.TextField(field_value, mask=None, is_one_sent=False, split_by_space=False, **kwargs)[source]

Bases: textflint.input_layer.component.field.field.Field

A helper class that represents input string that to be modified.

Text that Sample contains parsed in data set, TextField provides multiple methods for Sample to modify.

Support sentence level and word level modification, default using word level API.

text_processor = <textflint.common.preprocess.en_processor.EnProcessor object>
__init__(field_value, mask=None, is_one_sent=False, split_by_space=False, **kwargs)[source]
Parameters
  • field_value (str|list) – Sentence string or tokenized words.

  • mask (list) – list of mask values

  • is_one_sent (bool) – whether input is a sentence

  • split_by_space (boo) – whether tokenize sentence by split space

  • kwargs

pos_of_word_index(desired_word_idx)[source]

Get pos tag of given index.

Parameters

desired_word_idx (int) – desire index to get pos tag

Returns

pos tag of word of desired_word_idx.

replace_at_indices(indices, new_items)[source]

Replace words at indices and set their mask to MODIFIED_MASK.

Parameters
  • indices ([int|listslice]) –

    each index can be int indicate replace single item

    or their list like [1, 2, 3].

    each index can be list like (0,3) indicate replace items

    from 0 to 3(not included) or their list like [(0, 3), (5,6)]

    each index can be slice which would be convert to list.

  • new_items ([str|list|tuple]) – items corresponding indices.

Returns

Replaced TextField object.

replace_at_index(index, new_items)[source]

Replace words at indices and set their mask to MODIFIED_MASK.

Parameters
  • index (intlistslice) –

    can be int indicate replace single item or their list like [1, 2, 3] can be list like (0,3) indicate replace items

    from 0 to 3(not included) or their list like [(0, 3), (5,6)]

    can be slice which would be convert to list.

  • new_items (str|listtuple) – items corresponding index.

Returns

Replaced TextField object.

delete_at_indices(indices)[source]

Delete words at indices and remove their mask value.

Parameters

indices ([int|list|slice]) –

each index can be int indicate replace single item

or their list like [1, 2, 3].

each index can be list like (0,3) indicate replace items

from 0 to 3(not included) or their list like [(0, 3), (5,6)]

each index can be slice which would be convert to list.

Returns

Modified TextField object.

delete_at_index(index)[source]

Delete words at index and remove their mask value.

Parameters

index (int|list|slice) –

can be int indicate replace single item or their list like [1, 2, 3] can be list like (0,3) indicate replace items

from 0 to 3(not included) or their list like [(0, 3), (5,6)]

can be slice which would be convert to list.

Returns

Modified TextField object.

insert_before_indices(indices, new_items)[source]

Insert words before indices.

Parameters
  • indices ([int]) –

    can be int indicate replace single item or their list like [1, 2, 3] can be list like (0,3) indicate replace items

    from 0 to 3(not included) or their list like [(0, 3), (5,6)]

    can be slice which would be convert to list.

  • new_items ([str|list|tuple]) – items corresponding index.

Returns

new TextField object.

insert_before_index(index, new_items)[source]

Insert words before index and remove their mask value.

Parameters
  • index (int) –

    can be int indicate replace single item or their list like [1, 2, 3] can be list like (0,3) indicate replace items

    from 0 to 3(not included) or their list like [(0, 3), (5,6)]

    can be slice which would be convert to list.

  • new_items (str|list|tuple) – items corresponding index.

Returns

new TextField object.

insert_after_indices(indices, new_items)[source]

Insert words after indices.

Parameters
  • indices ([int]) –

    can be int indicate replace single item or their list like [1, 2, 3] can be list like (0,3) indicate replace items

    from 0 to 3(not included) or their list like [(0, 3), (5,6)]

    can be slice which would be convert to list.

  • new_items ([str|list|tuple]) – items corresponding index.

Returns

new TextField object.

insert_after_index(index, new_items)[source]

Insert words before index and remove their mask value.

Parameters
  • index (int) –

    can be int indicate replace single item or their list like [1, 2, 3] can be list like (0,3) indicate replace items

    from 0 to 3(not included) or their list like [(0, 3), (5,6)]

    can be slice which would be convert to list.

  • new_items (str|list|tuple) – items corresponding index.

Returns

new TextField object.

swap_at_index(first_index, second_index)[source]

Swap items between first_index and second_index of origin_list

Parameters
  • first_index (int) – index of first item

  • second_index (int) – index of second item

Returns

Modified TextField object.

property pos_tagging

Get POS tags.

Example:

given sentence 'All things in their being are good for something.'

>> [('All', 'DT'),
    ('things', 'NNS'),
    ('in', 'IN'),
    ('their', 'PRP$'),
    ('being', 'VBG'),
    ('are', 'VBP'),
    ('good', 'JJ'),
    ('for', 'IN'),
    ('something', 'NN'),
    ('.', '.')]
Returns

Tokenized tokens with their POS tags.

property ner

Get NER tags.

Example:

given sentence 'Lionel Messi is a football player from Argentina.'

>>[('Lionel Messi', 0, 2, 'PERSON'),
   ('Argentina', 7, 8, 'LOCATION')]
Returns

A list of tuples, (entity, start, end, label)

property dependency_parsing

Dependency parsing.

Example:

given sentence: 'The quick brown fox jumps over the lazy dog.'

>>
    The     DT      4       det
    quick   JJ      4       amod
    brown   JJ      4       amod
    fox     NN      5       nsubj
    jumps   VBZ     0       root
    over    IN      9       case
    the     DT      9       det
    lazy    JJ      9       amod
    dog     NN      5       obl
Returns

A list of tuples, (token, pos, target, type)

textflint.input_layer.component.sample.sample.abstractmethod(funcobj)[source]

A decorator indicating abstract methods.

Requires that the metaclass is ABCMeta or derived from it. A class that has a metaclass derived from ABCMeta cannot be instantiated unless all of its abstract methods are overridden. The abstract methods can be called using any of the normal ‘super’ call mechanisms.

Usage:

class C(metaclass=ABCMeta):

@abstractmethod def my_abstract_method(self, …):