Skip to content

Helpers.syntax()

Javi Jiménez edited this page Jun 26, 2016 · 1 revision

A method for sentence matching a array of rules

Example

import { syntax } from 'ava-ia/lib/helpers'

const RULES = [
  'translate [Preposition]? [Demonym]',
  'translate * [Preposition] [Demonym]',
];

const match = syntax(state.sentence, RULES);

Basic matching

term-term matches use normalised & non-normalised text as a direct lookup:

let matches = nlp.text('John eats glue!').match('john eats glue')
match[0].text()
//"John eats glue"

POS matching

you can loosen a search by any matching part-of-speech, allowing you to find all the things john eats, for example:

let matches = syntax(state.sentence, ['john eats [Noun]'])

Alias matching

you can loosen a search further, for words that 'mean' the same, using the fledgling nlp_compromise 'alias' feature. Different conjugations, forms, and synonyms are tentatively supported.

syntax(state.sentence, ['john ~eat~ glue'])

Wildcard matching

The . character means 'any one term'.

syntax(state.sentence, ['john . glue'])

The * means 'all terms until'. It may be 0.

syntax(state.sentence, ['john * eats'])

Optional matching

The ? character at the end of a word means it isn't necessary to be there.

syntax(state.sentence, ['john always? eats glue'])

syntax(state.sentence, ['john [Adverb]? eats glue'])

List of options

(word1|word2) parentheses allow listing possible matches for the word

syntax(state.sentence, ['john (eats|sniffs|wears) .']);

Location flags

A leading ^ character means 'at the start of a sentence'.

syntax(state.sentence, ['^john eats ...']);

An ending $ character means 'must be at the end of the sentence'.

syntax(state.sentence, ['eats glue$'])

Definition

'use strict';

import Compromise from 'nlp_compromise';

export default (sentence, rules) => {
  if (!Array.isArray(rules)) rules = [rules];
  let match;
  const rootSentence = Compromise.text(sentence).root();

  rules.map( rule => {
    const matches = Compromise.text(rootSentence).match(rule);
    if (matches.length > 0 && matches[0] !== null) match = matches[0].text()
  });

  return (match);
};

Feel free to offer new features, improvements or anything you can think of. This project makes sense with your participation and experience using Ava.

Clone this wiki locally