natural 7.1.0 → 8.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -43,6 +43,7 @@ export class TfIdf {
43
43
  constructor (deserialized?: Record<string, unknown>)
44
44
  idf (term: string, force?: boolean): number
45
45
  addDocument (document: string | string[] | Record<string, string>, key?: Record<string, any> | any, restoreCache?: boolean): void
46
+ removeDocument (key: any): boolean
46
47
  addFileSync (path: string, encoding?: string, key?: string, restoreCache?: boolean): void
47
48
  tfidf (terms: string | string[], d: number): number
48
49
  tfidfs (terms: string | string[], callback?: TfIdfCallback): number[]
@@ -136,9 +136,6 @@ export class TokenizerJa extends Tokenizer {
136
136
  }
137
137
 
138
138
  export class SentenceTokenizer extends Tokenizer {
139
- tokenize (text: string): string[]
140
- }
141
-
142
- export class SentenceTokenizerNew extends Tokenizer {
139
+ constructor (abbreviations: string[], sentenceDemarkers?: string[])
143
140
  tokenize (text: string): string[]
144
141
  }
@@ -46,4 +46,4 @@ exports.WordPunctTokenizer = require('./regexp_tokenizer').WordPunctTokenizer
46
46
  exports.TreebankWordTokenizer = require('./treebank_word_tokenizer')
47
47
  exports.TokenizerJa = require('./tokenizer_ja')
48
48
  exports.SentenceTokenizer = require('./sentence_tokenizer')
49
- exports.SentenceTokenizerNew = require('./sentence_tokenizer_parser')
49
+ exports.SentenceTokenizerNew = require('./sentence_tokenizer')
@@ -1,5 +1,5 @@
1
1
  /*
2
- Copyright (c) 2011, Chris Umbel
2
+ Copyright (c) 2024, Hugo W.L. ter Doest
3
3
 
4
4
  Permission is hereby granted, free of charge, to any person obtaining a copy
5
5
  of this software and associated documentation files (the "Software"), to deal
@@ -20,31 +20,177 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20
20
  THE SOFTWARE.
21
21
  */
22
22
 
23
- 'use strict'
24
-
25
23
  const Tokenizer = require('./tokenizer')
26
24
 
25
+ // Strings that will be used to create placeholders
26
+ const NUM = 'NUMBER'
27
+ const DELIM = 'DELIM'
28
+ const URI = 'URI'
29
+ const ABBREV = 'ABBREV'
30
+
27
31
  const DEBUG = false
28
32
 
33
+ function generateUniqueCode (base, index) {
34
+ // Surround the placeholder with {{}} to prevent shorter numbers to be recognized
35
+ // in larger numbers
36
+ return `{{${base}_${index}}}`
37
+ }
38
+
39
+ function escapeRegExp (string) {
40
+ return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
41
+ }
42
+
29
43
  class SentenceTokenizer extends Tokenizer {
30
- tokenize (text) {
31
- // Break string up in to sentences based on punctation and quotation marks
32
- // See https://gist.github.com/Hugo-ter-Doest/4ed21fb7eb5077814d998fa61a726566
33
- // for a breakdown of the regular expression
34
- let tokens = text.match(/(?<=\s+|^)["'‘“'"[({⟨]?(.*?[.?!…]|.+)(\s[.?!…])*["'’”'"\])}⟩]?(?=\s+|$)/g)
44
+ constructor (abbreviations) {
45
+ super()
46
+ if (abbreviations) {
47
+ this.abbreviations = abbreviations
48
+ } else {
49
+ this.abbreviations = []
50
+ }
51
+ this.replacementMap = null
52
+ this.replacementCounter = 0
53
+ }
54
+
55
+ replaceUrisWithPlaceholders (text) {
56
+ const urlPattern = /(https?:\/\/\S+|www\.\S+|ftp:\/\/\S+|(mailto:)?[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}|file:\/\/\S+)/gi
57
+
58
+ const modifiedText = text.replace(urlPattern, (match) => {
59
+ const placeholder = generateUniqueCode(URI, this.replacementCounter++)
60
+ this.replacementMap.set(placeholder, match)
61
+ return placeholder
62
+ })
35
63
 
36
- DEBUG && console.log('SentenceTokenizer.tokenize: ' + tokens)
64
+ return modifiedText
65
+ }
66
+
67
+ replaceAbbreviations (text) {
68
+ if (this.abbreviations.length === 0) {
69
+ return text
70
+ }
71
+ const pattern = new RegExp(`(${this.abbreviations.map(abbrev => escapeRegExp(abbrev)).join('|')})`, 'gi')
72
+ const replacedText = text.replace(pattern, match => {
73
+ const code = generateUniqueCode(ABBREV, this.replacementCounter++)
74
+ this.replacementMap.set(code, match)
75
+ return code
76
+ })
77
+
78
+ return replacedText
79
+ }
80
+
81
+ replaceDelimitersWithPlaceholders (text) {
82
+ // Regular expression for sentence delimiters optionally followed by a bracket or quote
83
+ // Multiple delimiters with spaces in between are allowed
84
+ // The expression makes sure that the sentence delimiter group ends with a sentence delimiter
85
+ const delimiterPattern = /([.?!… ]*)([.?!…])(["'”’)}\]]?)/g
86
+ const modifiedText = text.replace(delimiterPattern, (match, p1, p2, p3) => {
87
+ const placeholder = generateUniqueCode(DELIM, this.replacementCounter++)
88
+ this.delimiterMap.set(placeholder, p1 + p2 + p3)
89
+ return placeholder
90
+ })
37
91
 
38
- if (!tokens) {
92
+ return modifiedText
93
+ }
94
+
95
+ splitOnPlaceholders (text, placeholders) {
96
+ if (this.delimiterMap.size === 0) {
39
97
  return [text]
40
98
  }
41
99
 
42
- // remove unecessary white space
43
- tokens = tokens.map(Function.prototype.call, String.prototype.trim)
100
+ const keys = Array.from(this.delimiterMap.keys())
101
+ const pattern = new RegExp(`(${keys.map(escapeRegExp).join('|')})`)
102
+ const parts = text.split(pattern)
103
+
104
+ const sentences = []
105
+ for (let i = 0; i < parts.length; i += 2) {
106
+ const sentence = parts[i]
107
+ const placeholder = parts[i + 1] || ''
108
+ sentences.push(sentence + placeholder)
109
+ }
110
+
111
+ return sentences
112
+ }
113
+
114
+ replaceNumbersWithCode (text) {
115
+ // Regular expression to match numbers, including decimal points and commas
116
+ const numberPattern = /\b\d{1,3}(?:,\d{3})*(?:\.\d+)?\b/g
117
+
118
+ const replacedText = text.replace(numberPattern, match => {
119
+ const code = generateUniqueCode(NUM, this.replacementCounter++)
120
+ this.replacementMap.set(code, match)
121
+ return code
122
+ })
123
+
124
+ return replacedText
125
+ }
126
+
127
+ revertReplacements (text) {
128
+ let originalText = text
129
+ for (const [placeholder, replacement] of this.replacementMap.entries()) {
130
+ const pattern = new RegExp(escapeRegExp(placeholder), 'g')
131
+ originalText = originalText.replace(pattern, replacement)
132
+ }
133
+
134
+ return originalText
135
+ }
136
+
137
+ revertDelimiters (text) {
138
+ let originalText = text
139
+ for (const [placeholder, replacement] of this.delimiterMap.entries()) {
140
+ const pattern = new RegExp(escapeRegExp(placeholder), 'g')
141
+ originalText = originalText.replace(pattern, replacement)
142
+ }
143
+
144
+ return originalText
145
+ }
146
+
147
+ tokenize (text) {
148
+ this.replacementCounter = 0
149
+ this.replacementMap = new Map()
150
+ this.delimiterMap = new Map()
151
+
152
+ DEBUG && console.log('---Start of sentence tokenization-----------------------')
153
+ DEBUG && console.log('Original input: >>>' + text + '<<<')
154
+ // Replace abbreviations
155
+ const result1 = this.replaceAbbreviations(text)
156
+ DEBUG && console.log('Phase 1: replacing abbreviations: ' + JSON.stringify(result1))
157
+
158
+ // Replace URIs
159
+ const result2 = this.replaceUrisWithPlaceholders(result1)
160
+ DEBUG && console.log('Phase 2: replacing URIs: ' + JSON.stringify(result2))
161
+
162
+ // Replace delimiters followed by optional quotes, brackets, and braces
163
+ const result3 = this.replaceNumbersWithCode(result2)
164
+ DEBUG && console.log('Phase 3: replacing numbers with placeholders: ' + JSON.stringify(result3))
165
+
166
+ // Replace delimiters followed by optional quotes, brackets, and braces
167
+ const result4 = this.replaceDelimitersWithPlaceholders(result3)
168
+ DEBUG && console.log('Phase 4: replacing delimiters with placeholders: ' + JSON.stringify(result4))
169
+
170
+ // Split on placeholders for sentence delimiters
171
+ const sentences = this.splitOnPlaceholders(result4)
172
+ DEBUG && console.log('Phase 5: splitting into sentences on placeholders: ' + JSON.stringify(sentences))
173
+
174
+ // Replace back all abbreviations, URIs, and delimiters
175
+ const newSentences = sentences.map(s => {
176
+ const s1 = this.revertReplacements(s)
177
+ return this.revertDelimiters(s1)
178
+ })
179
+ DEBUG && console.log('Phase 6: replacing back abbreviations, URIs, numbers and delimiters: ' + JSON.stringify(newSentences))
180
+
181
+ const trimmedSentences = this.trim(newSentences)
182
+ DEBUG && console.log('Phase 7: trimming array of empty sentences: ' + JSON.stringify(trimmedSentences))
44
183
 
45
- DEBUG && console.log('SentenceTokenizer.tokenize: tokens after removing whitespace ' + tokens)
184
+ const trimmedSentences2 = trimmedSentences.map(sent => sent.trim())
185
+ DEBUG && console.log('Phase 8: trimming sentences from surrounding whitespace: ' + JSON.stringify(trimmedSentences2))
186
+ DEBUG && console.log('---End of sentence tokenization--------------------------')
187
+ DEBUG && console.log('---Replacement map---------------------------------------')
188
+ DEBUG && console.log([...this.replacementMap.entries()])
189
+ DEBUG && console.log('---Delimiter map-----------------------------------------')
190
+ DEBUG && console.log([...this.delimiterMap.entries()])
191
+ DEBUG && console.log('---------------------------------------------------------')
46
192
 
47
- return this.trim(tokens)
193
+ return trimmedSentences2
48
194
  }
49
195
  }
50
196
 
@@ -1,13 +1,16 @@
1
1
  /*
2
- Copyright (c) 2020, Hugo ter Doest
2
+ Copyright (c) 2011, Chris Umbel
3
+
3
4
  Permission is hereby granted, free of charge, to any person obtaining a copy
4
5
  of this software and associated documentation files (the "Software"), to deal
5
6
  in the Software without restriction, including without limitation the rights
6
7
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
8
  copies of the Software, and to permit persons to whom the Software is
8
9
  furnished to do so, subject to the following conditions:
10
+
9
11
  The above copyright notice and this permission notice shall be included in
10
12
  all copies or substantial portions of the Software.
13
+
11
14
  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
12
15
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
13
16
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -19,13 +22,29 @@ THE SOFTWARE.
19
22
 
20
23
  'use strict'
21
24
 
22
- const parser = require('./parser_sentence_tokenizer')
23
-
24
25
  const Tokenizer = require('./tokenizer')
25
26
 
27
+ const DEBUG = false
28
+
26
29
  class SentenceTokenizer extends Tokenizer {
27
30
  tokenize (text) {
28
- return (parser.parse(text))
31
+ // Break string up in to sentences based on punctation and quotation marks
32
+ // See https://gist.github.com/Hugo-ter-Doest/4ed21fb7eb5077814d998fa61a726566
33
+ // for a breakdown of the regular expression
34
+ let tokens = text.match(/(?<=\s+|^)["'‘“'"[({⟨]?(.*?[.?!…]|.+)(\s[.?!…])*["'’”'"\])}⟩]?(?=\s+|$)/g)
35
+
36
+ DEBUG && console.log('SentenceTokenizer.tokenize: ' + tokens)
37
+
38
+ if (!tokens) {
39
+ return [text]
40
+ }
41
+
42
+ // remove unecessary white space
43
+ tokens = tokens.map(Function.prototype.call, String.prototype.trim)
44
+
45
+ DEBUG && console.log('SentenceTokenizer.tokenize: tokens after removing whitespace ' + tokens)
46
+
47
+ return this.trim(tokens)
29
48
  }
30
49
  }
31
50
 
@@ -7,6 +7,8 @@ const knownAbbreviations = [
7
7
  'c/o',
8
8
  'dept.',
9
9
  'D.I.Y.',
10
+ 'Dr.',
11
+ 'e.g.',
10
12
  'est.',
11
13
  'E.T.A.',
12
14
  'Inc.',
@@ -19,7 +21,8 @@ const knownAbbreviations = [
19
21
  'tel.',
20
22
  'temp.',
21
23
  'vet.',
22
- 'vs.'
24
+ 'vs.',
25
+ 'i.e.'
23
26
  ]
24
27
 
25
28
  exports.knownAbbreviations = knownAbbreviations
@@ -23,6 +23,7 @@ THE SOFTWARE.
23
23
  'use strict'
24
24
 
25
25
  exports.stopwords = require('./stopwords').words
26
+ exports.abbreviations = require('./abbreviations_en').knownAbbreviations
26
27
  exports.ShortestPathTree = require('./shortest_path_tree')
27
28
  exports.LongestPathTree = require('./longest_path_tree')
28
29
  exports.DirectedEdge = require('./directed_edge')
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "natural",
3
3
  "description": "General natural language (tokenizing, stemming (English, Russian, Spanish), part-of-speech tagging, sentiment analysis, classification, inflection, phonetics, tfidf, WordNet, jaro-winkler, Levenshtein distance, Dice's Coefficient) facilities for node.",
4
- "version": "7.1.0",
4
+ "version": "8.0.1",
5
5
  "homepage": "https://github.com/NaturalNode/natural",
6
6
  "repository": {
7
7
  "type": "git",