UNPKG

compromise

Version:

modest natural language processing

434 lines (357 loc) β€’ 23.9 kB
<!-- πŸ€– generated by scripts/docs.js β€” do not edit by hand. --> # Compromise API Reference Every method returns a new **View** (a sub-selection of the document) unless noted, so calls chain: `nlp(text).match('#Verb').toPastTense().text()`. Methods are grouped by what they do. Method availability depends on the [build tier](concepts.md): `compromise/one` (tokenize), `compromise/two` (+tags & contractions), and the default `compromise` / `compromise/three` (+ all selections below). ## Core methods _(available on every View)_ - **`.case`** _[getter]_ β€” preserve the case of the original, ignoring the case of the replacement - **`.possessives`** _[getter]_ β€” preserve whether the original was a possessive - **`.tags`** _[getter]_ β€” preserve all of the tags of the original, regardless of the tags of the replacement ### Utils - **`.found`** _[getter]_ β€” is this document empty? - **`.docs`** _[getter]_ β€” get a list of term objects for this view - **`.document`** _[getter]_ β€” get the full parsed text - **`.pointer`** _[getter]_ β€” the indexes for the current view - **`.fullPointer`** _[getter]_ β€” explicit indexes for the current view - **`.methods`** _[getter]_ β€” access internal library methods - **`.model`** _[getter]_ β€” access internal library data - **`.hooks`** _[getter]_ β€” which compute methods run by default - **`.isView`** _[getter]_ β€” helper for detecting a compromise object - **`.length`** _[getter]_ β€” the number of matches (or sentences) - **`.update(pointer)`** β€” create a new view, from this document - **`.toView(pointer)`** β€” turn a Verb or Noun view into a normal one - **`.fromText(text)`** β€” create a new document - **`.termList()`** β€” .docs [alias] - **`.compute(method)`** β€” run a named operation on the document - **`.clone(shallow?)`** β€” deep-copy the document, so that no references remain ### Loops - **`.forEach(fn)`** β€” run a function on each phrase, as an individual document - **`.map(fn, emptyResult?)`** β€” run each phrase through a function, and create a new document - **`.filter(fn)`** β€” return only the phrases that return true - **`.find(fn)`** β€” return a document with only the first phrase that matches - **`.some(fn)`** β€” return true or false if there is one matching phrase - **`.random(n?)`** β€” sample a subset of the results ### Accessors - **`.terms(n?)`** β€” split-up results by each individual term - **`.groups(name?)`** β€” grab a specific named capture group - **`.eq(n)`** β€” use only the nth result - **`.first(n?)`** β€” use only the first result(s) - **`.last(n?)`** β€” use only the last result(s) - **`.firstTerms()`** β€” get the first word in each match - **`.lastTerms()`** β€” get the end word in each match - **`.slice(start, end?)`** β€” grab a subset of the results - **`.all()`** β€” return the whole original document ('zoom out') - **`.fullSentences()`** β€” return the full original sentence for each match - **`.none()`** β€” return an empty view - **`.isDoc(view?)`** β€” are these two views of the same document? - **`.wordCount()`** β€” count the # of terms in each match ### Match - **`.match(match, group?, options?)`** β€” return matching patterns in this doc - **`.matchOne(match, group?, options?)`** β€” return only the first match - **`.has(match, group?, options?)`** β€” Return a boolean if this match exists - **`.if(match, group?, options?)`** β€” return each current phrase, only if it contains this match - **`.ifNo(match, group?, options?)`** β€” Filter-out any current phrases that have this match - **`.before(match, group?, options?)`** β€” return the terms before each match - **`.after(match, group?, options?)`** β€” return the terms after each match - **`.lookBehind(match, group?, options?)`** β€” alias of .before() - **`.lookBefore(match, group?, options?)`** β€” alias of .before() - **`.lookAhead(match, group?, options?)`** β€” alias of .after() - **`.lookAfter(match, group?, options?)`** β€” alias of .after() - **`.growLeft(match, group?, options?)`** β€” add any immediately-preceding matches to the view - **`.growRight(match, group?, options?)`** β€” add any immediately-following matches to the view - **`.grow(match, group?, options?)`** β€” expand the view with any left-or-right matches - **`.sweep(match, opts?)`** β€” apply a sequence of match objects to the document - **`.splitOn(match?, group?)`** β€” .split() [alias] - **`.splitBefore(match?, group?)`** β€” separate everything after the match as a new phrase - **`.splitAfter(match?, group?)`** β€” separate everything before the word, as a new phrase - **`.split(match?, group?)`** β€” splitAfter() alias ### Case - **`.toLowerCase()`** β€” turn every letter of every term to lower-cse - **`.toUpperCase()`** β€” turn every letter of every term to upper case - **`.toTitleCase()`** β€” upper-case the first letter of each term - **`.toCamelCase()`** β€” remove whitespace and title-case each term ### Insert - **`.concat(input)`** β€” add these new things to the end - **`.insertBefore(input, opts?)`** β€” add these words before each match. Moves the sentence's capital and any opening punctuation onto the new words, unless `{ agree: false }` - **`.prepend(input, opts?)`** β€” insertBefore() alias - **`.insertAfter(text, opts?)`** β€” add these words after each match. Moves any closing punctuation onto the new words, unless `{ agree: false }` - **`.append(text, opts?)`** β€” insertAfter() alias - **`.insert(text)`** β€” insertAfter() alias - **`.remove(match?, opts?)`** β€” fully remove these terms from the document. Repairs the capital and punctuation around them, unless `{ agree: false }` - **`.delete(match)`** β€” alias for .remove() - **`.replace(from, to?, keep?)`** β€” search and replace match with new content - **`.replaceWith(to, keep?)`** β€” substitute-in new content. Keeps the sentence's capital and the punctuation around the old words, unless `{ agree: false }` - **`.unique()`** β€” remove any duplicate matches - **`.reverse()`** β€” reverse the order of the matches, but not the words - **`.sort(method?)`** β€” re-arrange the order of the matches (in place) - **`.normalize(options?)`** β€” cleanup various aspects of the words ### Whitespace - **`.pre(str?, concat?)`** β€” add this punctuation or whitespace before each match - **`.post(str?, concat?)`** β€” add this punctuation or whitespace after each match - **`.trim()`** β€” remove start and end whitespace - **`.hyphenate()`** β€” connect words with hyphen, and remove whitespace - **`.dehyphenate()`** β€” remove hyphens between words, and set whitespace - **`.deHyphenate()`** β€” alias for .dehyphenate() - **`.toQuotations(start?, end?)`** β€” add quotation marks around selections - **`.toQuotation(start?, end?)`** β€” alias for toQuotations() - **`.toParentheses(start?, end?)`** β€” add parentheses around selections ### Output - **`.text(options?)`** β€” return the document as text - **`.json(options?)`** β€” pull out desired metadata from the document - **`.debug()`** β€” pretty-print the current document and its tags - **`.out(format?)`** β€” some named output formats - **`.html(toHighlight)`** β€” produce an html string - **`.wrap(matches)`** β€” produce an html string ### Pointers - **`.union(match)`** β€” return all matches without duplicates - **`.and(match)`** β€” .union() alias - **`.intersection(match)`** β€” return only duplicate matches - **`.not(match, options?)`** β€” return all results except for this - **`.difference(match, options?)`** β€” .not() alias - **`.complement(match)`** β€” get everything that is not a match - **`.settle(match)`** β€” remove overlaps in matches ### Tag - **`.tag(tag, reason?)`** β€” Give all terms the given tag - **`.tagSafe(tag, reason?)`** β€” Only apply tag to terms if it is consistent with current tags - **`.unTag(tag, reason?)`** β€” Remove this term from the given terms - **`.canBe(tag)`** β€” return only the terms that can be this tag ### Cache - **`.cache(options?)`** β€” freeze the current state of the document, for speed-purposes - **`.uncache(options?)`** β€” un-freezes the current state of the document, so it may be transformed - **`.freeze()`** β€” prevent current tags from being removed - **`.unfreeze()`** β€” allow current tags to be changed [default] - **`.lookup(trie, opts?)`** β€” quick find for an array of string matches - **`.autoFill()`** β€” assume any type-ahead prefixes - **`.contractions(n?)`** β€” return any multi-word terms, like "didn't" - **`.contract()`** β€” contract words that can combine, like "did not" - **`.confidence()`** β€” Average measure of tag confidence - **`.swap(fromLemma, toLemma, guardTag?)`** β€” smart-replace root forms - **`.expand()`** β€” turn "i've" into "i have" ## Selections (compromise/three) These return specialised sub-views with extra methods. e.g. `doc.verbs().toPastTense()`. ### Selection methods on any View - **`.clauses(n?)`** β€” split-up results into multi-term phrases - **`.chunks()`** β€” split-up noun-phrase and verb-phrases - **`.normalize(options?)`** β€” clean-up the document, in various ways - **`.redact(opts?, blockStr?, keepTags?)`** β€” remove any people, places, and organizations - **`.hyphenated(n?)`** β€” return all terms connected with a hyphen or dash like `'wash-out'` - **`.hashTags(n?)`** β€” return terms like `'#nlp'` - **`.emails(n?)`** β€” return terms like `'hi@compromise.cool'` - **`.emoji(n?)`** β€” return terms like `πŸ’‹` - **`.emoticons(n?)`** β€” return terms like `:)` - **`.atMentions(n?)`** β€” return terms like `'@nlp_compromise'` - **`.urls(n?)`** β€” return terms like `'compromise.cool'` - **`.pronouns(n?)`** β€” return terms like `'he'` - **`.conjunctions(n?)`** β€” return terms like `'but'` - **`.prepositions(n?)`** β€” return terms like `'of'` - **`.honorifics(n?)`** β€” return terms like `'Dr.'` - **`.abbreviations(n?)`** β€” return terms like `'st.'` - **`.phoneNumbers(n?)`** β€” return terms like `'(939) 555-0113'` - **`.addresses(n?)`** β€” return terms like `'23 Park Avenue'` - **`.acronyms(n?)`** β€” return terms like `'FBI'` - **`.parentheses(n?)`** β€” return anything inside (parentheses) - **`.possessives(n?)`** β€” return terms like "Spencer's" - **`.quotations(n?)`** β€” return any terms inside 'quotation marks' - **`.slashes(n?)`** β€” return any slashed terms like 'love/hate' - **`.adjectives(n?)`** β€” return words like "clean" - **`.adverbs(n?)`** β€” return words like "quickly" - **`.nouns(n?, opts?)`** β€” return noun phrases in the view - **`.numbers(n?, opts?)`** β€” return any numbers in the view - **`.percentages(n?, opts?)`** β€” return any percentages in the view - **`.money(n?)`** β€” return monetary amounts as a Money view - **`.fractions(n?, opts?)`** β€” return any fractions in the view - **`.sentences(n?, opts?)`** β€” return full sentences in the view - **`.questions(n?, opts?)`** β€” find full sentences of any questions in the view - **`.verbs(n?)`** β€” return any subsequent terms tagged as a Verb - **`.people(n?)`** β€” return person names like `'John A. Smith'` - **`.places(n?)`** β€” return location names like `'Paris, France'` - **`.organizations(n?)`** β€” return companies and org names like `'Google Inc.'` - **`.topics(n?)`** β€” return people, places, and organizations ### `.nouns()` β†’ - **`.parse(n?)`** β€” grab the parsed noun-phrase - **`.isPlural()`** β€” return only plural nouns - **`.adjectives()`** β€” get any adjectives describing this noun - **`.toPlural(opts?)`** β€” 'a football captain' β†’ 'football captains'. Drops 'a/an' and makes the next verb agree ('is' β†’ 'are', 'barks' β†’ 'bark'), unless `{ agree: false }` - **`.toSingular(opts?)`** β€” 'sells seashells' β†’ 'sells a seashell'. Adds 'a/an' to a bare plural and makes the next verb agree ('are' β†’ 'is', 'bark' β†’ 'barks'), unless `{ agree: false }` ### `.numbers()` β†’ - **`.parse(n?)`** β€” grab the parsed number - **`.get(n?)`** β€” grab the parsed number - **`.isOrdinal()`** β€” return only ordinal numbers - **`.isCardinal()`** β€” return only cardinal numbers - **`.isUnit(units)`** β€” return only numbers with the given unit(s), like 'km' - **`.isValid()`** β€” drop matches that do not parse to a usable number, like `thousand thousand`, `21th` or `1/0` - **`.toNumber()`** β€” convert number to `5` or `5th` - **`.toLocaleString()`** β€” add commas, or nicer formatting for numbers - **`.toText()`** β€” convert number to `five` or `fifth`; a slash-fraction like `1/2` becomes `one half` - **`.toCardinal()`** β€” convert number to `five` or `5` - **`.toOrdinal()`** β€” convert number to `fifth` or `5th` - **`.toFraction()`** β€” convert decimals to reduced fractions, such as `0.25` β†’ `1/4`, or percentages to fractions over 100, such as `4.5%` β†’ `4.5/100`; returns a Fractions selection - **`.toPercentage()`** β€” convert decimals to percentages, such as `0.25` β†’ `25%`; existing percentages remain unchanged. Returns a Numbers selection of percentages. - **`.toDecimal()`** β€” convert selected percentages to decimals, such as `25%` β†’ `0.25`; returns a Numbers selection of the converted values - **`.isEqual()`** β€” return numbers with this value - **`.greaterThan(min)`** β€” return numbers bigger than n - **`.lessThan(max)`** β€” return numbers smaller than n - **`.between(min, max)`** β€” return numbers between min and max - **`.set(n, opts?)`** β€” set number to n. The counted noun, and its verb, follow ('two dogs bark' β†’ 'one dog barks'), unless `{ agree: false }` - **`.add(n, opts?)`** β€” increase number by n. The counted noun, and its verb, follow, unless `{ agree: false }` - **`.subtract(n, opts?)`** β€” decrease number by n. The counted noun, and its verb, follow, unless `{ agree: false }` - **`.increment()`** β€” increase number by 1 - **`.decrement()`** β€” decrease number by 1 ### `.percentages()` β†’ Uses the Numbers methods above. `.toFraction()` mutates the document and returns only the converted fractions, retaining their fraction methods on subsets: ```js const doc = nlp('We saved 25% on books and 50% on pens.') const fractions = doc.percentages().toFraction() fractions.eq(0).toPercentage() doc.text() // 'We saved 25% on books and 50/100 on pens.' ``` Conversions can round-trip through all three forms: ```js const doc = nlp('0.25') doc.numbers().toPercentage().toFraction().toDecimal() doc.text() // '0.25' ``` Fraction-to-percentage conversion rounds to two decimal places except for fractions over 100, so some round trips lose precision. ### `.money()` β†’ Money extends Numbers. Arithmetic, formatting, comparisons, and the selections listed below return Money views, so methods can chain with `.currency()`. Transformations mutate the original document while retaining currency symbols and words. ```js const doc = nlp('i paid $5.32 for a pizza slice') const amount = doc.money().add(1) amount.text() // '$6.32' amount.currency() // ['dollar'] doc.text() // 'i paid $6.32 for a pizza slice' ``` - **`.parse(n?)`** β€” array of `{ currency, num }` objects - **`.get(n?)`** β€” array of numeric amounts, including when selecting one index - **`.currency(n?)`** β€” array of currency names or codes; these are not normalized to a single standard - **`.json(n?)`** β€” ordinary JSON records with an additional `money: { currency, num }` property; also accepts JSON output options - **`.set(n)`** β€” set each amount; accepts a number or number words - **`.add(n)`**, **`.plus(n)`** β€” increase each amount; accepts a number or number words - **`.subtract(n)`**, **`.minus(n)`** β€” decrease each amount by a number - **`.increment()`**, **`.decrement()`** β€” increase or decrease each amount by one - **`.isEqual(n)`**, **`.equals(n)`** β€” select amounts equal to n - **`.greaterThan(n)`**, **`.lessThan(n)`** β€” select amounts strictly above or below n - **`.between(min, max)`**, **`.isBetween(min, max)`** β€” select amounts strictly between the bounds - **`.toNumber()`** β€” convert number words to digits, retaining the currency - **`.toText()`** β€” convert digits to number words; recognized prefix symbols become currency words, such as `$5` β†’ `five dollars` - **`.toLocaleString()`**, **`.toNice()`** β€” format amounts using the runtime's default locale, retaining the currency - **`.isOrdinal()`**, **`.isCardinal()`** β€” select by the number's ordinal/cardinal tags - **`.units()`** β€” select words tagged as units, including currency words such as `dollars` - **`.isUnit(units)`** β€” filter by unit text, using the same arguments as Numbers - **`.first(n?)`**, **`.last(n?)`**, **`.eq(n)`**, **`.slice(start, end?)`**, **`.filter(fn)`** β€” retain the Money class when selecting amounts - **`.clone()`** β€” create an independent Money view and document - **`.numbers(n?)`**, **`.values(n?)`** β€” explicitly select the numeric portions as Numbers Comparisons and arithmetic use major-unit values. `50 cents` parses as `0.5`; adding `0.01` produces `51 cents`, while adding `1` produces `150 cents`. `.numbers()` still returns the written numeric value (`50`). Compound amounts such as `5 dollars and 32 cents` parse as one amount (`5.32`) when the major and minor units are compatible. Dollars/euros with cents and pounds with pence/pennies are supported; different currencies remain separate selections. Compound arithmetic preserves both parts and carries or borrows minor units: `5 dollars and 90 cents` plus `0.2` becomes `6 dollars and 10 cents`. A leading minus applies to the whole compound amount, including `-0 dollars and 68 cents`. Compound formatting conversions remain unchanged. Money arithmetic uses decimal addition to avoid binary rounding tails such as `0.30000000000000004`. Numeric output preserves existing decimal places and adds precision when needed: `$5.00 + 1` becomes `$6.00`, and `$1.00 + 0.001` becomes `$1.001`. Commas, currency symbols, and word forms are retained; currency words agree with their new amounts. Results still use JavaScript numbers and their precision limits. Minor-unit multipliers live in `nlp.world().model.three.decimalCurrencies`. Defaults are `0.01` for `cent`, `penny`, `pence`, `centavo`, `centime`, `paisa`, `ore`, and `ΓΆre`. Names use lowercase keys; common plural forms are recognized. The cent symbol `Β’` uses the `cent` entry. Without an explicit qualifier, currency names remain the written names (e.g. `cent`), since these units do not uniquely identify a national currency. ```js const rates = nlp.world().model.three.decimalCurrencies rates.cent = 0.001 // affects subsequent parsing, comparisons, and arithmetic rates.token = 0.01 // recognize custom amounts such as '25 tokens' ``` Explicit `CAD` and `USD` qualifiers take precedence over generic currency names. They can precede or follow an amount, or be attached to a numeric amount: `CAD $50`, `$50 CAD`, and `$50CAD` all report `CAD` from `.currency()`. Code matching is case-insensitive and reported codes are uppercase. Qualifiers are retained through arithmetic and conversions. `50 cents CAD` still parses as `0.5`, while a bare `$50` reports `dollar` without guessing a national currency. Cent amounts round-trip through words: `50Β’` β†’ `fifty cents` β†’ `50 cents` retains its value of `0.5`. Configured custom units follow the same conversion behavior. Changes apply to existing views on their next operation as well. Multipliers must be positive finite numbers; missing or invalid values default to `1`. Removing a custom unit also removes recognition supplied by this table. Compound carry/borrow uses the configured minor-unit multiplier. No exchange-rate conversion is performed. ### `.fractions()` β†’ - **`.parse(n?)`** β€” grab the parsed number - **`.get(n?)`** β€” grab the parsed number - **`.toDecimal()`** β€” convert '1/4' to `0.25` - **`.toFraction()`** β€” convert 'one fourth' to `1/4` - **`.toOrdinal()`** β€” convert `1/4` to `one fourth` - **`.toCardinal()`** β€” convert `1/4` to `one out of four` - **`.toText()`** β€” convert `1/4` to `one fourth` - **`.toPercentage(n?)`** β€” convert fractions such as `1/4` or `one half` to `25%` or `50%`; optionally convert only the nth fraction. Mutates the document and returns a View of the processed selection. Fractions over 100 preserve the numerator's precision; other denominators round to two decimal places. Unparseable fractions and zero denominators remain unchanged. ### `.sentences()` β†’ - **`.parse(n?)`** β€” grab the parsed sentence - **`.toPastTense()`** β€” 'will go' β†’ 'went' - **`.toPresentTense()`** β€” 'walked' β†’ 'walks' - **`.toFutureTense()`** β€” 'walked' β†’ 'will walk' - **`.toInfinitive()`** β€” 'walks' β†’ 'walk' - **`.toNegative()`** β€” 'he is cool' β†’ 'he is not cool' - **`.toPositive()`** β€” 'he isn't cool' -> 'he is cool' - **`.isQuestion()`** β€” keep only questions - **`.isExclamation()`** β€” keep only sentences with an exclamation-mark - **`.isStatement()`** β€” remove questions, and exclamations ### `.people()` β†’ - **`.parse()`** β€” get first/last/middle names ### `.verbs()` β†’ - **`.parse(n?)`** β€” grab the parsed verb-phrase - **`.subjects()`** β€” grab what [doing] the verb - **`.adverbs()`** β€” return the adverbs describing this verb - **`.isSingular()`** β€” return only singular nouns - **`.isPlural()`** β€” return only plural nouns - **`.isImperative()`** β€” only verbs that are instructions - **`.toInfinitive()`** β€” 'walks' β†’ 'walk' - **`.toPresentTense()`** β€” 'walked' β†’ 'walks' - **`.toPastTense()`** β€” 'will go' β†’ 'went' - **`.toFutureTense()`** β€” 'walked' β†’ 'will walk' - **`.toGerund()`** β€” 'walks' β†’ 'walking' - **`.toPastParticiple()`** β€” 'walks' β†’ 'has walked' - **`.conjugate()`** β€” return all forms of these verbs - **`.isNegative()`** β€” return verbs with 'not' - **`.isPositive()`** β€” only verbs without 'not' - **`.toPositive()`** β€” "didn't study" β†’ 'studied' - **`.toNegative()`** β€” 'went' β†’ 'did not go' ### `.acronyms()` β†’ - **`.strip()`** β€” 'F.B.I.' -> 'FBI' - **`.addPeriods()`** β€” 'FBI' -> 'F.B.I.' ### `.parentheses()` β†’ - **`.strip()`** β€” remove ( and ) punctuation ### `.possessives()` β†’ - **`.strip()`** β€” "spencer's" -> "spencer" ### `.quotations()` β†’ - **`.strip()`** β€” remove leading and trailing quotation marks ### `.slashes()` β†’ - **`.split()`** β€” turn 'love/hate' into 'love hate' ### `.adjectives()` β†’ - **`.adverbs()`** β€” get the words describing this adjective - **`.conjugate()`** β€” return all forms of these - **`.toComparative(n?)`** β€” 'quick' -> 'quicker' - **`.toSuperlative(n?)`** β€” 'quick' -> 'quickest' - **`.toAdverb(n?)`** β€” 'quick' -> 'quickly' - **`.toNoun(n?)`** β€” 'quick' -> 'quickness' ## Constructor methods (`nlp.*`) _(called on the imported `nlp` object, not a View)_ - **`nlp.tokenize(text, lexicon?)`** β€” interpret text without tagging - **`nlp.lazy(text, match?)`** β€” scan through text with minimal analysis - **`nlp.plugin(plugin)`** β€” mix in a compromise-plugin - **`nlp.extend(plugin)`** β€” mix-in a compromise plugin - **`nlp.parseMatch(match, opts?)`** β€” turn a match-string into json - **`nlp.world()`** β€” grab library internals - **`nlp.model()`** β€” grab library metadata - **`nlp.methods()`** β€” grab exposed library methods - **`nlp.hooks()`** β€” which compute functions run automatically - **`nlp.verbose(toLog?)`** β€” log our decision-making for debugging - **`nlp.version`** β€” current semver version of the library - **`nlp.addTags(tags)`** β€” connect new tags to tagset graph - **`nlp.addWords(words, isFrozen?)`** β€” add new words to internal lexicon - **`nlp.buildTrie(words)`** β€” turn a list of words into a searchable graph - **`nlp.buildNet(matches)`** β€” compile a set of match objects to a more optimized form - **`nlp.typeahead(words)`** β€” add words to the autoFill dictionary