Packages

class ChunkTokenizer extends Tokenizer

Tokenizes and flattens extracted NER chunks.

The ChunkTokenizer will split the extracted NER CHUNK type Annotations and will create TOKEN type Annotations. The result is then flattened, resulting in a single array.

For extended examples of usage, see the ChunkTokenizerTestSpec.

Example

import spark.implicits._
import com.johnsnowlabs.nlp.DocumentAssembler
import com.johnsnowlabs.nlp.annotators.{ChunkTokenizer, TextMatcher, Tokenizer}
import com.johnsnowlabs.nlp.annotators.sbd.pragmatic.SentenceDetector
import com.johnsnowlabs.nlp.util.io.ReadAs
import org.apache.spark.ml.Pipeline

val documentAssembler = new DocumentAssembler()
  .setInputCol("text")
  .setOutputCol("document")

val sentenceDetector = new SentenceDetector()
  .setInputCols(Array("document"))
  .setOutputCol("sentence")

val tokenizer = new Tokenizer()
  .setInputCols(Array("sentence"))
  .setOutputCol("token")

val entityExtractor = new TextMatcher()
  .setInputCols("sentence", "token")
  .setEntities("src/test/resources/entity-extractor/test-chunks.txt", ReadAs.TEXT)
  .setOutputCol("entity")

val chunkTokenizer = new ChunkTokenizer()
  .setInputCols("entity")
  .setOutputCol("chunk_token")

val pipeline = new Pipeline().setStages(Array(
    documentAssembler,
    sentenceDetector,
    tokenizer,
    entityExtractor,
    chunkTokenizer
  ))

val data = Seq(
  "Hello world, my name is Michael, I am an artist and I work at Benezar",
  "Robert, an engineer from Farendell, graduated last year. The other one, Lucas, graduated last week."
).toDF("text")
val result = pipeline.fit(data).transform(data)

result.selectExpr("entity.result as entity" , "chunk_token.result as chunk_token").show(false)
+-----------------------------------------------+---------------------------------------------------+
|entity                                         |chunk_token                                        |
+-----------------------------------------------+---------------------------------------------------+
|[world, Michael, work at Benezar]              |[world, Michael, work, at, Benezar]                |
|[engineer from Farendell, last year, last week]|[engineer, from, Farendell, last, year, last, week]|
+-----------------------------------------------+---------------------------------------------------+
Linear Supertypes
Tokenizer, AnnotatorApproach[TokenizerModel], CanBeLazy, DefaultParamsWritable, MLWritable, HasOutputAnnotatorType, HasOutputAnnotationCol, HasInputAnnotationCols, Estimator[TokenizerModel], PipelineStage, Logging, Params, Serializable, Serializable, Identifiable, AnyRef, Any
Ordering
  1. Grouped
  2. Alphabetic
  3. By Inheritance
Inherited
  1. ChunkTokenizer
  2. Tokenizer
  3. AnnotatorApproach
  4. CanBeLazy
  5. DefaultParamsWritable
  6. MLWritable
  7. HasOutputAnnotatorType
  8. HasOutputAnnotationCol
  9. HasInputAnnotationCols
  10. Estimator
  11. PipelineStage
  12. Logging
  13. Params
  14. Serializable
  15. Serializable
  16. Identifiable
  17. AnyRef
  18. Any
  1. Hide All
  2. Show All
Visibility
  1. Public
  2. All

Parameters

A list of (hyper-)parameter keys this annotator can take. Users can set and get the parameter values through setters and getters, respectively.

  1. val caseSensitiveExceptions: BooleanParam

    Whether to care for case sensitiveness in exceptions (Default: true)

    Whether to care for case sensitiveness in exceptions (Default: true)

    Definition Classes
    Tokenizer
  2. val contextChars: StringArrayParam

    Character list used to separate from token boundaries (Default: Array(".", ",", ";", ":", "!", "?", "*", "-", "(", ")", "\"", "'"))

    Character list used to separate from token boundaries (Default: Array(".", ",", ";", ":", "!", "?", "*", "-", "(", ")", "\"", "'"))

    Definition Classes
    Tokenizer
  3. val exceptions: StringArrayParam

    Words that won't be affected by tokenization rules

    Words that won't be affected by tokenization rules

    Definition Classes
    Tokenizer
  4. val exceptionsPath: ExternalResourceParam

    Path to file containing list of exceptions

    Path to file containing list of exceptions

    Definition Classes
    Tokenizer
  5. val infixPatterns: StringArrayParam

    Regex patterns that match tokens within a single target.

    Regex patterns that match tokens within a single target. groups identify different sub-tokens. multiple defaults

    Infix patterns must use regex group. Notice each group will result in separate token

    Example:

    import org.apache.spark.ml.Pipeline
    import com.johnsnowlabs.nlp.annotators.Tokenizer
    import com.johnsnowlabs.nlp.DocumentAssembler
    
    val textDf = sqlContext.sparkContext.parallelize(Array("l'une d'un l'un, des l'extrême des l'extreme")).toDF("text")
    val documentAssembler = new DocumentAssembler().setInputCol("text").setOutputCol("sentences")
    val tokenizer = new Tokenizer().setInputCols("sentences").setOutputCol("tokens").setInfixPatterns(Array("([\\p{L}\\w]+'{1})([\\p{L}\\w]+)"))
    new Pipeline().setStages(Array(documentAssembler, tokenizer)).fit(textDf).transform(textDf).select("tokens.result").show(false)

    This will yield: l', une, d', un, l', un, , , des, l', extrême, des, l', extreme

    Definition Classes
    Tokenizer
  6. val maxLength: IntParam

    Set the maximum allowed length for each token

    Set the maximum allowed length for each token

    Definition Classes
    Tokenizer
  7. val minLength: IntParam

    Set the minimum allowed length for each token

    Set the minimum allowed length for each token

    Definition Classes
    Tokenizer
  8. val prefixPattern: Param[String]

    Regex with groups and begins with \\A to match target prefix.

    Regex with groups and begins with \\A to match target prefix. Overrides contextCharacters Param

    Definition Classes
    Tokenizer
  9. val splitChars: StringArrayParam

    Character list used to separate from the inside of tokens

    Character list used to separate from the inside of tokens

    Definition Classes
    Tokenizer
  10. val splitPattern: Param[String]

    Pattern to separate from the inside of tokens.

    Pattern to separate from the inside of tokens. takes priority over splitChars.

    This pattern will be applied to the tokens which where extracted with the target pattern previously

    Example:

    import org.apache.spark.ml.Pipeline
    
    import com.johnsnowlabs.nlp.annotators.Tokenizer
    
    import com.johnsnowlabs.nlp.DocumentAssembler
    
    val textDf = sqlContext.sparkContext.parallelize(Array("Tokens in this-text will#be#split on hashtags-and#dashes")).toDF("text")
    
    val documentAssembler = new DocumentAssembler().setInputCol("text").setOutputCol("sentences")
    
    val tokenizer = new Tokenizer().setInputCols("sentences").setOutputCol("tokens").setSplitPattern("-|#")
    
    new Pipeline().setStages(Array(documentAssembler, tokenizer)).fit(textDf).transform(textDf).select("tokens.result").show(false)

    This will yield: Tokens, in, this, text, will, be, split, on, hashtags, and, dashes

    Definition Classes
    Tokenizer
  11. val suffixPattern: Param[String]

    Regex with groups and ends with \\z to match target suffix.

    Regex with groups and ends with \\z to match target suffix. Overrides contextCharacters Param

    Definition Classes
    Tokenizer
  12. val targetPattern: Param[String]

    Pattern to grab from text as token candidates.

    Pattern to grab from text as token candidates. (Default: "\\S+")

    Defaults to: "\\S+" which means anything not a space will be matched and considered as a token candidate, This will cause text to be split on on white spaces to yield token candidates.

    This rule will be added to the BREAK_PATTERN varaible, which is used to yield token candidates.

    import org.apache.spark.ml.Pipeline
    import com.johnsnowlabs.nlp.annotators.Tokenizer
    import com.johnsnowlabs.nlp.DocumentAssembler
    
    val textDf = sqlContext.sparkContext.parallelize(Array("I only consider lowercase characters and NOT UPPERCASED and only the numbers 0,1, to 7 as tokens but not 8 or 9")).toDF("text")
    val documentAssembler = new DocumentAssembler().setInputCol("text").setOutputCol("sentences")
    val tokenizer = new Tokenizer().setInputCols("sentences").setOutputCol("tokens").setTargetPattern("a-z-0-7")
    new Pipeline().setStages(Array(documentAssembler, tokenizer)).fit(textDf).transform(textDf).select("tokens.result").show(false)

    This will yield: only, consider, lowercase, characters, and, and, only, the, numbers, 0, 1, to, 7, as, tokens, but, not, or

    Definition Classes
    Tokenizer

Annotator types

Required input and expected output annotator types

  1. val inputAnnotatorTypes: Array[AnnotatorType]

    Input Annotator Type : CHUNK

    Input Annotator Type : CHUNK

    Definition Classes
    ChunkTokenizerTokenizerHasInputAnnotationCols
  2. val outputAnnotatorType: AnnotatorType

    Output Annotator Type : TOKEN

    Output Annotator Type : TOKEN

    Definition Classes
    ChunkTokenizerTokenizerHasOutputAnnotatorType

Members

  1. type AnnotatorType = String
    Definition Classes
    HasOutputAnnotatorType
  1. def beforeTraining(spark: SparkSession): Unit
    Definition Classes
    AnnotatorApproach
  2. def buildRuleFactory: RuleFactory

    Build rule factory which combines all defined parameters to build regex that is applied to tokens

    Build rule factory which combines all defined parameters to build regex that is applied to tokens

    Definition Classes
    Tokenizer
  3. final def clear(param: Param[_]): ChunkTokenizer.this.type
    Definition Classes
    Params
  4. final def copy(extra: ParamMap): Estimator[TokenizerModel]
    Definition Classes
    AnnotatorApproach → Estimator → PipelineStage → Params
  5. val description: String

    Annotator that identifies points of analysis in a useful manner

    Annotator that identifies points of analysis in a useful manner

    Definition Classes
    TokenizerAnnotatorApproach
  6. def explainParam(param: Param[_]): String
    Definition Classes
    Params
  7. def explainParams(): String
    Definition Classes
    Params
  8. final def extractParamMap(): ParamMap
    Definition Classes
    Params
  9. final def extractParamMap(extra: ParamMap): ParamMap
    Definition Classes
    Params
  10. final def fit(dataset: Dataset[_]): TokenizerModel
    Definition Classes
    AnnotatorApproach → Estimator
  11. def fit(dataset: Dataset[_], paramMaps: Seq[ParamMap]): Seq[TokenizerModel]
    Definition Classes
    Estimator
    Annotations
    @Since( "2.0.0" )
  12. def fit(dataset: Dataset[_], paramMap: ParamMap): TokenizerModel
    Definition Classes
    Estimator
    Annotations
    @Since( "2.0.0" )
  13. def fit(dataset: Dataset[_], firstParamPair: ParamPair[_], otherParamPairs: ParamPair[_]*): TokenizerModel
    Definition Classes
    Estimator
    Annotations
    @Since( "2.0.0" ) @varargs()
  14. final def get[T](param: Param[T]): Option[T]
    Definition Classes
    Params
  15. final def getDefault[T](param: Param[T]): Option[T]
    Definition Classes
    Params
  16. def getInputCols: Array[String]

    returns

    input annotations columns currently used

    Definition Classes
    HasInputAnnotationCols
  17. def getLazyAnnotator: Boolean
    Definition Classes
    CanBeLazy
  18. final def getOrDefault[T](param: Param[T]): T
    Definition Classes
    Params
  19. final def getOutputCol: String

    Gets annotation column name going to generate

    Gets annotation column name going to generate

    Definition Classes
    HasOutputAnnotationCol
  20. def getParam(paramName: String): Param[Any]
    Definition Classes
    Params
  21. final def hasDefault[T](param: Param[T]): Boolean
    Definition Classes
    Params
  22. def hasParam(paramName: String): Boolean
    Definition Classes
    Params
  23. final def isDefined(param: Param[_]): Boolean
    Definition Classes
    Params
  24. final def isSet(param: Param[_]): Boolean
    Definition Classes
    Params
  25. val lazyAnnotator: BooleanParam
    Definition Classes
    CanBeLazy
  26. def onTrained(model: TokenizerModel, spark: SparkSession): Unit
    Definition Classes
    AnnotatorApproach
  27. val optionalInputAnnotatorTypes: Array[String]
    Definition Classes
    HasInputAnnotationCols
  28. lazy val params: Array[Param[_]]
    Definition Classes
    Params
  29. def save(path: String): Unit
    Definition Classes
    MLWritable
    Annotations
    @Since( "1.6.0" ) @throws( ... )
  30. final def set[T](param: Param[T], value: T): ChunkTokenizer.this.type
    Definition Classes
    Params
  31. final def setInputCols(value: String*): ChunkTokenizer.this.type
    Definition Classes
    HasInputAnnotationCols
  32. def setInputCols(value: Array[String]): ChunkTokenizer.this.type

    Overrides required annotators column if different than default

    Overrides required annotators column if different than default

    Definition Classes
    HasInputAnnotationCols
  33. def setLazyAnnotator(value: Boolean): ChunkTokenizer.this.type
    Definition Classes
    CanBeLazy
  34. final def setOutputCol(value: String): ChunkTokenizer.this.type

    Overrides annotation column name when transforming

    Overrides annotation column name when transforming

    Definition Classes
    HasOutputAnnotationCol
  35. def toString(): String
    Definition Classes
    Identifiable → AnyRef → Any
  36. def train(dataset: Dataset[_], recursivePipeline: Option[PipelineModel]): TokenizerModel

    Clears out rules and constructs a new rule for every combination of rules provided .

    Clears out rules and constructs a new rule for every combination of rules provided . The strategy is to catch one token per regex group. User may add its own groups if needs targets to be tokenized separately from the rest

    Definition Classes
    ChunkTokenizerTokenizerAnnotatorApproach
  37. final def transformSchema(schema: StructType): StructType

    requirement for pipeline transformation validation.

    requirement for pipeline transformation validation. It is called on fit()

    Definition Classes
    AnnotatorApproach → PipelineStage
  38. val uid: String
    Definition Classes
    ChunkTokenizerTokenizer → Identifiable
  39. def write: MLWriter
    Definition Classes
    DefaultParamsWritable → MLWritable

Parameter setters

  1. def addContextChars(v: String): ChunkTokenizer.this.type

    Add one character string to rip off from tokens, such as parenthesis or question marks.

    Add one character string to rip off from tokens, such as parenthesis or question marks. Ignored if using prefix, infix or suffix patterns.

    Definition Classes
    Tokenizer
  2. def addException(value: String): ChunkTokenizer.this.type

    Add a single exception

    Add a single exception

    Definition Classes
    Tokenizer
  3. def addInfixPattern(value: String): ChunkTokenizer.this.type

    Add an extension pattern regex with groups to the top of thsetExceptionse rules (will target first, from more specific to the more general).

    Add an extension pattern regex with groups to the top of thsetExceptionse rules (will target first, from more specific to the more general).

    Definition Classes
    Tokenizer
  4. def addSplitChars(v: String): ChunkTokenizer.this.type

    One character string to split tokens inside, such as hyphens.

    One character string to split tokens inside, such as hyphens. Ignored if using infix, prefix or suffix patterns.

    Definition Classes
    Tokenizer
  5. def getExceptions: Array[String]

    Definition Classes
    Tokenizer
  6. def setContextChars(v: Array[String]): ChunkTokenizer.this.type

    List of 1 character string to rip off from tokens, such as parenthesis or question marks.

    List of 1 character string to rip off from tokens, such as parenthesis or question marks. Ignored if using prefix, infix or suffix patterns.

    Definition Classes
    Tokenizer
  7. def setExceptions(value: Array[String]): ChunkTokenizer.this.type

    List of tokens to not alter at all.

    List of tokens to not alter at all. Allows composite tokens like two worded tokens that the user may not want to split.

    Definition Classes
    Tokenizer
  8. def setInfixPatterns(value: Array[String]): ChunkTokenizer.this.type

    Set a list of Regex patterns that match tokens within a single target.

    Set a list of Regex patterns that match tokens within a single target. Groups identify different sub-tokens. multiple defaults

    Definition Classes
    Tokenizer
  9. def setMaxLength(value: Int): ChunkTokenizer.this.type

    Get the maximum allowed length for each token

    Get the maximum allowed length for each token

    Definition Classes
    Tokenizer
  10. def setMinLength(value: Int): ChunkTokenizer.this.type

    Set the minimum allowed length for each token

    Set the minimum allowed length for each token

    Definition Classes
    Tokenizer
  11. def setPrefixPattern(value: String): ChunkTokenizer.this.type

    Regex to identify subtokens that come in the beginning of the token.

    Regex to identify subtokens that come in the beginning of the token. Regex has to start with \\A and must contain groups (). Each group will become a separate token within the prefix. Defaults to non-letter characters. e.g. quotes or parenthesis

    Definition Classes
    Tokenizer
  12. def setSplitChars(v: Array[String]): ChunkTokenizer.this.type

    List of 1 character string to split tokens inside, such as hyphens.

    List of 1 character string to split tokens inside, such as hyphens. Ignored if using infix, prefix or suffix patterns.

    Definition Classes
    Tokenizer
  13. def setSplitPattern(value: String): ChunkTokenizer.this.type

    Regex pattern to separate from the inside of tokens.

    Regex pattern to separate from the inside of tokens. Takes priority over splitChars.

    Definition Classes
    Tokenizer
  14. def setSuffixPattern(value: String): ChunkTokenizer.this.type

    Regex to identify subtokens that are in the end of the token.

    Regex to identify subtokens that are in the end of the token. Regex has to end with \\z and must contain groups (). Each group will become a separate token within the prefix. Defaults to non-letter characters. e.g. quotes or parenthesis

    Definition Classes
    Tokenizer
  15. def setTargetPattern(value: String): ChunkTokenizer.this.type

    Set a basic regex rule to identify token candidates in text.

    Set a basic regex rule to identify token candidates in text.

    Definition Classes
    Tokenizer

Parameter getters

  1. def getCaseSensitiveExceptions(value: Boolean): Boolean

    Whether to follow case sensitiveness for matching exceptions in text

    Whether to follow case sensitiveness for matching exceptions in text

    Definition Classes
    Tokenizer
  2. def getContextChars: Array[String]

    List of 1 character string to rip off from tokens, such as parenthesis or question marks.

    List of 1 character string to rip off from tokens, such as parenthesis or question marks. Ignored if using prefix, infix or suffix patterns.

    Definition Classes
    Tokenizer
  3. def getInfixPatterns: Array[String]

    Add an extension pattern regex with groups to the top of the rules (will target first, from more specific to the more general).

    Add an extension pattern regex with groups to the top of the rules (will target first, from more specific to the more general).

    Definition Classes
    Tokenizer
  4. def getMaxLength(value: Int): Int

    Get the maximum allowed length for each token

    Get the maximum allowed length for each token

    Definition Classes
    Tokenizer
  5. def getMinLength(value: Int): Int

    Get the minimum allowed length for each token

    Get the minimum allowed length for each token

    Definition Classes
    Tokenizer
  6. def getPrefixPattern: String

    Regex to identify subtokens that come in the beginning of the token.

    Regex to identify subtokens that come in the beginning of the token. Regex has to start with \\A and must contain groups (). Each group will become a separate token within the prefix. Defaults to non-letter characters. e.g. quotes or parenthesis

    Definition Classes
    Tokenizer
  7. def getSplitChars: Array[String]

    List of 1 character string to split tokens inside, such as hyphens.

    List of 1 character string to split tokens inside, such as hyphens. Ignored if using infix, prefix or suffix patterns.

    Definition Classes
    Tokenizer
  8. def getSplitPattern: String

    List of 1 character string to split tokens inside, such as hyphens.

    List of 1 character string to split tokens inside, such as hyphens. Ignored if using infix, prefix or suffix patterns.

    Definition Classes
    Tokenizer
  9. def getSuffixPattern: String

    Regex to identify subtokens that are in the end of the token.

    Regex to identify subtokens that are in the end of the token. Regex has to end with \\z and must contain groups (). Each group will become a separate token within the prefix. Defaults to non-letter characters. e.g. quotes or parenthesis

    Definition Classes
    Tokenizer
  10. def getTargetPattern: String

    Basic regex rule to identify a candidate for tokenization.

    Basic regex rule to identify a candidate for tokenization. Defaults to \\S+ which means anything not a space

    Definition Classes
    Tokenizer
  11. def setCaseSensitiveExceptions(value: Boolean): ChunkTokenizer.this.type

    Whether to follow case sensitiveness for matching exceptions in text

    Whether to follow case sensitiveness for matching exceptions in text

    Definition Classes
    Tokenizer
  12. def setExceptionsPath(path: String, readAs: Format = ReadAs.TEXT, options: Map[String, String] = Map("format" -> "text")): ChunkTokenizer.this.type

    Path to txt file with list of token exceptions

    Path to txt file with list of token exceptions

    Definition Classes
    Tokenizer