Skip to content
プロジェクト

概要

Split {Japanese, English} text into sentences.

AI・機械学習

この数値の測り方

計測したスター増加

24時間
0
7日間
0
15日間
0
1か月
履歴を収集中

期間ごとの純増数です。期間は重複しており、日別の値ではありません。未計測の値は空欄です。スター数は注目度の指標であり、品質の保証ではありません。

sentence-splitter

Split {Japanese, English} text into sentences.

What is sentence?

This library split next text into 3 sentences.

We are talking about pens.
He said "This is a pen. I like it".
I could relate to that statement.

Result is:

Sentence Image

You can check actual AST in online playground.

Second sentence includes "This is a pen. I like it", but this library can not split it into new sentence. The reason is "..." and 「...」 text is ambiguous as a sentence or a proper noun. Also, HTML does not have suitable semantics for conversation.

As a result, The second line will be one sentence, but sentence-splitter add a contexts info to the sentence node.

{
    "type": "Sentence",
    "children": [
      {
        "type": "Str",
        "value": "He said \"This is a pen. I like it\""
      },
      ...
    ],
    "contexts": [
        {
            "type": "PairMark",
            "pairMark": {
                "key": "double quote",
                "start": "\"",
                "end": "\""
            },
            "range": [
                8,
                33
            ],
            ...
        ]
    ]
}

Probably, textlint rule should handle the "..." and 「...」 text after parsing sentences by sentence-splitter.

Installation

npm install sentence-splitter

Usage

export interface SeparatorParserOptions {
    /**
     * Recognize each characters as separator
     * Example [".", "!", "?"]
     */
    separatorCharacters?: string[]
}

export interface AbbrMarkerOptions {
    language?: Language;
}

export interface splitOptions {
    /**
     * Separator & AbbrMarker options
     */
    SeparatorParser?: SeparatorParserOptions;
    AbbrMarker?: AbbrMarkerOptions;
}

/**
 * split `text` into Sentence nodes.
 * This function return array of Sentence nodes.
 */
export declare function split(text: string, options?: splitOptions): TxtParentNodeWithSentenceNode["children"];

/**
 * Convert Paragraph Node to Paragraph Node that includes Sentence Node.
 * Paragraph Node is defined in textlint's TxtAST.
 * See https://github.com/textlint/textlint/blob/master/docs/txtnode.md
 */
export declare function splitAST(paragraphNode: TxtParentNode, options?: splitOptions): TxtParentNodeWithSentenceNode;

See also TxtAST.

Example

Node

This node is based on TxtAST.

Node's type

  • Str: Str node has value. It is same as TxtAST's Str node.
  • Sentence: Sentence Node has Str, WhiteSpace, or Punctuation nodes as children
  • WhiteSpace: WhiteSpace Node has \n.
  • Punctuation: Punctuation Node has ., 。

Get these SentenceSplitterSyntax constants value from the module:

import { SentenceSplitterSyntax } from "sentence-splitter";

console.log(SentenceSplitterSyntax.Sentence);// "Sentence"

Node's interface

export type SentencePairMarkContext = {
  type: "PairMark";
  range: readonly [startIndex: number, endIndex: number];
  loc: {
    start: {
      line: number;
      column: number;
    };
    end: {
      line: number;
      column: number;
    };
  };
};
export type TxtSentenceNode = Omit<TxtParentNode, "type"> & {
    readonly type: "Sentence";
    readonly contexts?: TxtPairMarkNode[];
};
export type TxtWhiteSpaceNode = Omit<TxtTextNode, "type"> & {
    readonly type: "WhiteSpace";
};
export type TxtPunctuationNode = Omit<TxtTextNode, "type"> & {
    readonly type: "Punctuation";
};

Fore more details, Please see TxtAST.

Node layout

Node layout image.

This is 1st sentence. This is 2nd sentence.

<Sentence>
    <Str />                      |This is 1st sentence|
    <Punctuation />              |.|
</Sentence>
<WhiteSpace />                   | |
<Sentence>
    <Str />                      |This is 2nd sentence|
    <Punctuation />              |.|
</Sentence>

Note: This library will not split Str into Str and WhiteSpace(tokenize) Because, Tokenize need to implement language specific context.

For textlint rule

You can use splitAST for textlint rule. splitAST function can preserve original AST's position unlike split function.

import { splitAST, SentenceSplitterSyntax } from "sentence-splitter";

export default function(context, options = {}) {
    const { Syntax, RuleError, report, getSource } = context;
    return {
        [Syntax.Paragraph](node) {
            const parsedNode = splitAST(node);
            const sentenceNodes = parsedNode.children.filter(childNode => childNode.type === SentenceSplitterSyntax.Sentence);
            console.log(sentenceNodes); // => Sentence nodes
        }
    }
}

Examples

Difference from Intl.Segmenter

Intl.Segmenter with granularity: "sentence" also splits text into sentences. It is built into JavaScript runtimes and is a good choice when you only need sentence strings.

sentence-splitter is designed for linting tools like textlint, and it provides the following features that Intl.Segmenter does not have.

  • Return AST nodes(Sentence, Str, Punctuation, WhiteSpace) with range and loc(line and column)
  • Split a TxtAST Paragraph node with splitAST, so it works with Markdown and other formats supported by textlint
  • Handle abbreviations like Mr. and U.S.
  • Do not split a sentence inside pair marks like "..." and 「...」, and add contexts info to the sentence node
  • Return the same result in every runtime. The result of Intl.Segmenter depends on the ICU data of the runtime

For example, Node.js 22 (ICU 78.3) returns the following results.

Input Intl.Segmenter sentence-splitter
Mr. Smith went to Washington. He left. Mr. / Smith went to Washington. / He left. Mr. Smith went to Washington. / He left.
He said "This is a pen. I like it". I agree. He said "This is a pen. / I like it". / I agree. He said "This is a pen. I like it". / I agree.

Reference

This library use "Golden Rule" test of pragmatic_segmenter for testing.

Related Libraries

Tests

Run tests:

npm test

Create input.json from _input.md

npm run createInputJson

Update snapshots(output.json):

npm run updateSnapshot

Adding snapshot testcase

  1. Create test/fixtures/<test-case-name>/ directory
  2. Put test/fixtures/<test-case-name>/_input.md with testing content
  3. Run npm run updateSnapshot
  4. Check the test/fixtures/<test-case-name>/output.json
  5. If it is ok, commit it

Performance profile

The profile measures splitAST of each paragraph and split of each file on fixed sets of documents: the times, the allocation and the garbage collection, and the functions with the most CPU time. It keeps sentence-splitter from getting slower without anyone noticing.

Set Documents
small test/fixtures/*/_input.md of this repository
medium js-primer v7.0.0 (Japanese)
large Node.js v24.12.0 API documents (English)

Profile the working tree:

pnpm run profile

Compare master and the working tree. The comparison also lists the paragraphs and the files whose result differs:

pnpm run compare
# a quick check
pnpm run compare --set small,medium
# another base
pnpm run compare --base <ref>

The result is written to profile-result/ (profile.md, profile.json, and the CPU profiles that Chrome DevTools opens). medium and large are downloaded, and the build of a base is kept, in ~/.cache/sentence-splitter-profile.

The "Performance profile" workflow runs pnpm run compare on a pull request that changes src/, and writes the Markdown to the job summary. It does not fail on a difference. When a pull request changes the performance, paste the output of pnpm run compare into its description.

Contributing

  1. Fork it!
  2. Create your feature branch: git checkout -b my-new-feature
  3. Commit your changes: git commit -am 'Add some feature'
  4. Push to the branch: git push origin my-new-feature
  5. Submit a pull request :D

License

MIT

関連プロジェクトを探す

読み込み中…