Profile
Back to NewsBack
GitHub Trending 15 min
Reader Mode
spencermountain/compromise: modest natural-language processing

spencermountain/compromise: modest natural-language processing

compromise
modest natural language processing
npm install compromise

don't you find it strange,
    how easy text is to make,

     ᔐᖜ   and how hard it is to actually parse and use?

compromise tries its best to turn text into data.
it makes limited and sensible decisions.
it's not as smart as you'd think.

import nlp from 'compromise'

let doc = nlp('she sells seashells by the seashore.') doc.verbs().toPastTense() doc.text() // 'she sold seashells by the seashore.'

don't be fancy, at all:

if (doc.has('simon says #Verb')) {
  return true
}

grab parts of the text:

let doc = nlp(entireNovel)
doc.match('the #Adjective of times').text()
// "the blurst of times?"

and get data:

import plg from 'compromise-speech'
nlp.extend(plg)

let doc = nlp('Milwaukee has certainly had its share of visitors..') doc.compute('syllables') doc.places().json() /* [{ "text": "Milwaukee", "terms": [{ "normal": "milwaukee", "syllables": ["mil", "wau", "kee"] }] }] */

avoid the problems of brittle parsers:

let doc = nlp("we're not gonna take it..")

doc.has('gonna') // true doc.has('going to') // true (implicit)

// transform doc.contractions().expand() doc.text() // 'we are not going to take it..'

and whip stuff around like it's data:

let doc = nlp('ninety five thousand and fifty two')
doc.numbers().add(20)
doc.text()
// 'ninety five thousand and seventy two'

-because it actually is-

let doc = nlp('the purple dinosaur')
doc.nouns().toPlural()
doc.text()
// 'the purple dinosaurs'

Use it on the client-side:

<script src="https://unpkg.com/compromise"></script>
<script>
  var doc = nlp('two bottles of beer')
  doc.numbers().minus(1)
  document.body.innerHTML = doc.text()
  // 'one bottle of beer'
</script>

or likewise:

import nlp from 'compromise'

var doc = nlp('London is calling') doc.verbs().toNegative() // 'London is not calling'

compromise is ~250kb (minified):

it's pretty fast. It can run on keypress:

it works mainly by conjugating all forms of a basic word list.

The final lexicon is ~14,000 words:

you can read more about how it works, here. it's weird.

okay -

compromise/one

A tokenizer of words, sentences, and punctuation.

import nlp from 'compromise/one'

let doc = nlp("Wayne's World, party time") let data = doc.json() /* [{ normal:"wayne's world party time", terms:[{ text: "Wayne's", normal: "wayne" }, ... ] }] */

compromise/one splits your text up, wraps it in a handy API,

    and does nothing else -

/one is quick - most sentences take a 10th of a millisecond.

It can do ~1mb of text a second - or 10 wikipedia pages.

Infinite jest takes 3s.

You can also parallelize, or stream text to it with compromise-speed.

compromise/two

A part-of-speech tagger, and grammar-interpreter.

import nlp from 'compromise/two'

let doc = nlp("Wayne's World, party time") let str = doc.match('#Possessive #Noun').text() // "Wayne's World"

compromise/two automatically calculates the very basic grammar of each word.

this is more useful than people sometimes realize.

Light grammar helps you write cleaner templates, and get closer to the information.

compromise has 83 tags, arranged in a handsome graph.

#FirstName#Person#ProperNoun#Noun

you can see the grammar of each word by running doc.debug()

you can see the reasoning for each tag with nlp.verbose('tagger').

if you prefer Penn tags, you can derive them with:

let doc = nlp('welcome thrillho')
doc.compute('penn')
doc.json()

compromise/three

Phrase and sentence tooling.

import nlp from 'compromise/three'

let doc = nlp("Wayne's World, party time") let str = doc.people().normalize().text() // "wayne"

compromise/three is a set of tooling to zoom into and operate on parts of a text.

.numbers() grabs all the numbers in a document, for example - and extends it with new methods, like .subtract().

When you have a phrase, or group of words, you can see additional metadata about it with .json()

let doc = nlp('four out of five dentists')
console.log(doc.fractions().json())
/*[{
    text: 'four out of five',
    terms: [ [Object], [Object], [Object], [Object] ],
    fraction: { numerator: 4, denominator: 5, decimal: 0.8 }
  }
]*/
let doc = nlp('$4.09CAD')
doc.money().json()
/*[{
    text: '$4.09CAD',
    terms: [ [Object] ],
    number: { prefix: '$', num: 4.09, suffix: 'cad'}
  }
]*/

🤖 For AI agents & LLMs

Plain-text, copy-paste docs that render without JavaScript live in this repo:

API

Compromise/one

##### Output

  • .text() - return the document as text
  • .json() - return the document as data
  • .debug() - pretty-print the interpreted document
  • .out() - a named or custom output
  • .html({}) - output custom html tags for matches
  • .wrap({}) - produce custom output for document matches
##### Utils
  • .found _[getter]_ - is this document empty?
  • .docs _[getter]_ get term objects as json
  • .length _[getter]_ - count the # of characters in the document (string length)
  • .isView _[getter]_ - identify a compromise object
  • .compute() - run a named analysis on the document
  • .clone() - deep-copy the document, so that no references remain
  • .termList() - return a flat list of all Term objects in match
  • .cache({}) - freeze the current state of the document, for speed-purposes
  • .uncache() - un-freezes the current state of the document, so it may be transformed
  • .freeze({}) - prevent any tags from being removed, in these terms
  • .unfreeze({}) - allow tags to change again, as default
##### Accessors ##### Match

_(match methods use the match-syntax.)_

  • .match('') - return a new Doc, with this one as a parent
  • .not('') - return all results except for this
  • .matchOne('') - return only the first match
  • .if('') - return each current phrase, only if it contains this match ('only')
  • .ifNo('') - Filter-out any current phrases that have this match ('notIf')
  • .has('') - Return a boolean if this match exists
  • .before('') - return all terms before a match, in each phrase
  • .after('') - return all terms after a match, in each phrase
  • .union() - return combined matches without duplicates
  • .intersection() - return only duplicate matches
  • .complement() - get everything not in another match
  • .settle() - remove overlaps from matches
  • .growRight('') - add any matching terms immediately after each match
  • .growLeft('') - add any matching terms immediately before each match
  • .grow('') - add any matching terms before or after each match
  • .sweep(net) - apply a series of match objects to the document
  • .splitOn('') - return a Document with three parts for every match ('splitOn')
  • .splitBefore('') - partition a phrase before each matching segment
  • .splitAfter('') - partition a phrase after each matching segment
  • .join() - merge any neighbouring terms in each match
  • .joinIf(leftMatch, rightMatch) - merge any neighbouring terms under given conditions
  • [.lookup([])](https://observablehq.com/@spencermountain/compromise-match) - quick find for an array of string matches
  • .autoFill() - create type-ahead assumptions on the document
##### Tag
  • .tag('') - Give all terms the given tag
  • .tagSafe('') - Only apply tag to terms if it is consistent with current tags
  • .unTag('') - Remove this term from the given terms
  • .canBe('') - return only the terms that can be this tag
##### Case ##### Whitespace
  • .pre('') - add this punctuation or whitespace before each match
  • .post('') - 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
  • .toQuotations() - add quotation marks around these matches
  • .toParentheses() - add brackets around these matches
##### Loops
  • .map(fn) - run each phrase through a function, and create a new document
  • .forEach(fn) - run a function on each phrase, as an individual 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(fn) - sample a subset of the results
##### Insert ##### Transform
  • .sort('method') - re-arrange the order of the matches (in place)
  • .reverse() - reverse the order of the matches, but not the words
  • .unique() - remove any duplicate matches
##### Lib

_(these methods are on the main nlp object)_

compromise/two:

##### Contractions

compromise/three:

##### Nouns
  • .nouns() - return any subsequent terms tagged as a Noun
- .nouns().json() - overloaded output with noun metadata - .nouns().parse() - get tokenized noun-phrase - .nouns().isPlural() - return only plural nouns - .nouns().isSingular() - return only singular nouns - .nouns().toPlural() - 'football captain' → 'football captains' - .nouns().toSingular() - 'turnovers' → 'turnover' - .nouns().adjectives() - get any adjectives describing this noun

##### Verbs

  • .verbs() - return any subsequent terms tagged as a Verb
- .verbs().json() - overloaded output with verb metadata - .verbs().parse() - get tokenized verb-phrase - .verbs().subjects() - what is doing the verb action - .verbs().adverbs() - return the adverbs describing this verb. - .verbs().isSingular() - return singular verbs like 'spencer walks' - .verbs().isPlural() - return plural verbs like 'we walk' - .verbs().isImperative() - only instruction verbs like 'eat it!' - .verbs().toPastTense() - 'will go' → 'went' - .verbs().toPresentTense() - 'walked' → 'walks' - .verbs().toFutureTense() - 'walked' → 'will walk' - .verbs().toInfinitive() - 'walks' → 'walk' - .verbs().toGerund() - 'walks' → 'is walking' - .verbs().toPastParticiple() - 'drive' → 'had driven' - .verbs().conjugate() - return all conjugations of these verbs - .verbs().isNegative() - return verbs with 'not', 'never' or 'no' - .verbs().isPositive() - only verbs without 'not', 'never' or 'no' - .verbs().toNegative() - 'went' → 'did not go' - .verbs().toPositive() - "didn't study" → 'studied'

##### Numbers

- .numbers().parse() - get tokenized number phrase - .numbers().get() - get a simple javascript number - .numbers().json() - overloaded output with number metadata - .numbers().toNumber() - convert 'five' to 5 - .numbers().toLocaleString() - add commas, or nicer formatting for numbers - .numbers().toText() - convert '5' to five - .numbers().toOrdinal() - convert 'five' to fifth or 5th - .numbers().toCardinal() - convert 'fifth' to five or 5 - .numbers().isOrdinal() - return only ordinal numbers - .numbers().isCardinal() - return only cardinal numbers - .numbers().isEqual(n) - return numbers with this value - .numbers().greaterThan(min) - return numbers bigger than n - .numbers().lessThan(max) - return numbers smaller than n - .numbers().between(min, max) - return numbers between min and max - .numbers().isUnit(unit) - return only numbers in the given unit, like 'km' - .numbers().set(n) - set number to n - .numbers().add(n) - increase number by n - .numbers().subtract(n) - decrease number by n - .numbers().increment() - increase number by 1 - .numbers().decrement() - decrease number by 1 - .money().get() - retrieve the parsed amount(s) of money - .money().json() - currency + number info - .money().currency() - which currency the money is in - .fractions().parse() - get tokenized fraction - .fractions().get() - simple numerator, denominator data - .fractions().json() - json method overloaded with fractions data - .fractions().toDecimal() - '2/3' -> '0.66' - .fractions().normalize() - 'four out of 10' -> '4/10' - .fractions().toText() - '4/10' -> 'four tenths' - .fractions().toPercentage() - '4/10' -> '40%' - .percentages().get() - return the percentage number / 100 - .percentages().json() - json overloaded with percentage information - .percentages().toFraction() - '80%' -> '8/10'

##### Sentences

  • .sentences() - return a sentence class with additional methods
- .sentences().json() - overloaded output with sentence metadata - .sentences().toPastTense() - he walks -> he walked - .sentences().toPresentTense() - he walked -> he walks - .sentences().toFutureTense() -- he walks -> he will walk - .sentences().toInfinitive() -- verb root-form he walks -> he walk - .sentences().toNegative() - - he walks -> he didn't walk - .sentences().isQuestion() - return questions with a ? - .sentences().isExclamation() - return sentences with a ! - .sentences().isStatement() - return sentences without ? or !

##### Adjectives

- .adjectives().json() - get adjective metadata - .adjectives().conjugate() - return all inflections of these adjectives - .adjectives().adverbs() - get adverbs describing this adjective - .adjectives().toComparative() - 'quick' -> 'quicker' - .adjectives().toSuperlative() - 'quick' -> 'quickest' - .adjectives().toAdverb() - 'quick' -> 'quickly' - .adjectives().toNoun() - 'quick' -> 'quickness'

##### Misc selections

- .people().json() - get person-name metadata - .people().parse() - get person-name interpretation - .adverbs().json() - get adverb metadata - .acronyms().strip() - remove periods from acronyms - .acronyms().addPeriods() - add periods to acronyms - .parentheses().strip() - remove brackets - .possessives().strip() - "Spencer's" -> "Spencer" - .quotations().strip() - remove quotation marks - .slashes().split() - turn 'love/hate' into 'love hate'

.extend():

This library comes with a considerate, common-sense baseline for english grammar.

You're free to change, or lay-waste to any settings - which is the fun part actually.

the easiest part is just to suggest tags for any given words:

let myWords = {
  kermit: 'FirstName',
  fozzie: 'FirstName',
}
let doc = nlp(muppetText, myWords)

or make heavier changes with a compromise-plugin.

import nlp from 'compromise'
nlp.extend({
  // add new tags
  tags: {
    Character: {
      isA: 'Person',
      notA: 'Adjective',
    },
  },
  // add or change words in the lexicon
  words: {
    kermit: 'Character',
    gonzo: 'Character',
  },
  // change inflections
  irregulars: {
    get: {
      pastTense: 'gotten',
      gerund: 'gettin',
    },
  },
  // add new methods to compromise
  api: View => {
    View.prototype.kermitVoice = function () {
      this.sentences().prepend('well,')
      this.match('i [(am|was)]').prepend('um,')
      return this
    }
  },
})

Docs:

##### gentle introduction:

##### Documentation:

| Concepts | API | Plugins | | ------------------------------------------------------------------------------------------- | :---------------------------------------------------------------------------------------------: | -------------------------------------------------------------------------------------: | | Accuracy | Accessors | Adjectives | | Caching | Constructor-methods | Dates | | Case | Contractions | Export | | Filesize | Insert | Hash | | Internals | Json | Html | | Justification | Character Offsets | Keypress | | Lexicon | Loops | Ngrams | | Match-syntax | Match | Numbers | | Performance | Nouns | Paragraphs | | Plugins | Output | Scan | | Projects | Selections | Sentences | | Tagger | Sorting | Syllables | | Tags | Split | Pronounce | | Tokenization | Text | [Strict]

... (README truncated for length)

Chat with me