natural 7.1.0 → 8.0.0

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.
@@ -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,174 @@ 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
+ return `${base}_${index}`
35
+ }
36
+
37
+ function escapeRegExp (string) {
38
+ return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
39
+ }
40
+
29
41
  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)
42
+ constructor (abbreviations, sentenceDemarkers) {
43
+ super()
44
+ this.abbreviations = abbreviations
45
+ if (sentenceDemarkers) {
46
+ this.sentenceDemarkers = sentenceDemarkers
47
+ } else {
48
+ this.sentenceDemarkers = ['.', '!', '?']
49
+ }
50
+ this.replacementMap = null
51
+ this.replacementCounter = 0
52
+ }
53
+
54
+ replaceUrisWithPlaceholders (text) {
55
+ const urlPattern = /(https?:\/\/\S+|www\.\S+|ftp:\/\/\S+|(mailto:)?[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}|file:\/\/\S+)/gi
56
+
57
+ const modifiedText = text.replace(urlPattern, (match) => {
58
+ const placeholder = generateUniqueCode(URI, this.replacementCounter++)
59
+ this.replacementMap.set(placeholder, match)
60
+ return placeholder
61
+ })
35
62
 
36
- DEBUG && console.log('SentenceTokenizer.tokenize: ' + tokens)
63
+ return modifiedText
64
+ }
65
+
66
+ replaceAbbreviations (text) {
67
+ const pattern = new RegExp(`(${this.abbreviations.map(abbrev => escapeRegExp(abbrev)).join('|')})`, 'g')
68
+ const replacedText = text.replace(pattern, match => {
69
+ const code = generateUniqueCode(ABBREV, this.replacementCounter++)
70
+ this.replacementMap.set(code, match)
71
+ return code
72
+ })
73
+
74
+ return replacedText
75
+ }
76
+
77
+ replaceDelimitersWithPlaceholders (text) {
78
+ // Regular expression for sentence delimiters optionally followed by a bracket or quote
79
+ // Multiple delimiters with spaces in between are allowed
80
+ // The look ahead makes sure that there is punctuation symbol as next symbol
81
+ const delimiterPattern = /(?=[.?!…])([.?!… ]+)(["'”’)}\]]?)/g
82
+
83
+ const modifiedText = text.replace(delimiterPattern, (match, p1, p2) => {
84
+ const placeholder = generateUniqueCode(DELIM, this.replacementCounter++)
85
+ this.delimiterMap.set(placeholder, p1 + p2)
86
+ return placeholder
87
+ })
37
88
 
38
- if (!tokens) {
89
+ return modifiedText
90
+ }
91
+
92
+ splitOnPlaceholders (text, placeholders) {
93
+ if (this.delimiterMap.size === 0) {
39
94
  return [text]
40
95
  }
41
96
 
42
- // remove unecessary white space
43
- tokens = tokens.map(Function.prototype.call, String.prototype.trim)
97
+ const keys = Array.from(this.delimiterMap.keys())
98
+ const pattern = new RegExp(`(${keys.map(escapeRegExp).join('|')})`)
99
+ const parts = text.split(pattern)
100
+
101
+ const sentences = []
102
+ for (let i = 0; i < parts.length; i += 2) {
103
+ const sentence = parts[i]
104
+ const placeholder = parts[i + 1] || ''
105
+ sentences.push(sentence + placeholder)
106
+ }
107
+
108
+ return sentences
109
+ }
110
+
111
+ replaceNumbersWithCode (text) {
112
+ // Regular expression to match numbers, including decimal points and commas
113
+ const numberPattern = /\b\d{1,3}(?:,\d{3})*(?:\.\d+)?\b/g
114
+
115
+ const replacedText = text.replace(numberPattern, match => {
116
+ const code = generateUniqueCode(NUM, this.replacementCounter++)
117
+ this.replacementMap.set(code, match)
118
+ return code
119
+ })
120
+
121
+ return replacedText
122
+ }
123
+
124
+ revertReplacements (text) {
125
+ let originalText = text
126
+ for (const [placeholder, replacement] of this.replacementMap.entries()) {
127
+ const pattern = new RegExp(escapeRegExp(placeholder), 'g')
128
+ originalText = originalText.replace(pattern, replacement)
129
+ }
130
+
131
+ return originalText
132
+ }
133
+
134
+ revertDelimiters (text) {
135
+ let originalText = text
136
+ for (const [placeholder, replacement] of this.delimiterMap.entries()) {
137
+ const pattern = new RegExp(escapeRegExp(placeholder), 'g')
138
+ originalText = originalText.replace(pattern, replacement)
139
+ }
140
+
141
+ return originalText
142
+ }
143
+
144
+ tokenize (text) {
145
+ this.replacementCounter = 0
146
+ this.replacementMap = new Map()
147
+ this.delimiterMap = new Map()
148
+
149
+ DEBUG && console.log('---Start of sentence tokenization-----------------------')
150
+ DEBUG && console.log('Original input: >>>' + text + '<<<')
151
+ // Replace abbreviations
152
+ const result1 = this.replaceAbbreviations(text)
153
+ DEBUG && console.log('Phase 1: replacing abbreviations: ' + JSON.stringify(result1))
154
+
155
+ // Replace URIs
156
+ const result2 = this.replaceUrisWithPlaceholders(result1)
157
+ DEBUG && console.log('Phase 2: replacing URIs: ' + JSON.stringify(result2))
158
+
159
+ // Replace delimiters followed by optional quotes, brackets, and braces
160
+ const result3 = this.replaceNumbersWithCode(result2)
161
+ DEBUG && console.log('Phase 3: replacing numbers with placeholders: ' + JSON.stringify(result3))
162
+
163
+ // Replace delimiters followed by optional quotes, brackets, and braces
164
+ const result4 = this.replaceDelimitersWithPlaceholders(result3)
165
+ DEBUG && console.log('Phase 4: replacing delimiters with placeholders: ' + JSON.stringify(result4))
166
+
167
+ // Split on placeholders for sentence delimiters
168
+ const sentences = this.splitOnPlaceholders(result4)
169
+ DEBUG && console.log('Phase 5: splitting into sentences on placeholders: ' + JSON.stringify(sentences))
170
+
171
+ // Replace back all abbreviations, URIs, and delimiters
172
+ const newSentences = sentences.map(s => {
173
+ const s1 = this.revertReplacements(s)
174
+ return this.revertDelimiters(s1)
175
+ })
176
+ DEBUG && console.log('Phase 6: replacing back abbreviations, URIs, numbers and delimiters: ' + JSON.stringify(newSentences))
177
+
178
+ const trimmedSentences = this.trim(newSentences)
179
+ DEBUG && console.log('Phase 7: trimming array of empty sentences: ' + JSON.stringify(trimmedSentences))
44
180
 
45
- DEBUG && console.log('SentenceTokenizer.tokenize: tokens after removing whitespace ' + tokens)
181
+ const trimmedSentences2 = trimmedSentences.map(sent => sent.trim())
182
+ DEBUG && console.log('Phase 8: trimming sentences from surrounding whitespace: ' + JSON.stringify(trimmedSentences2))
183
+ DEBUG && console.log('---End of sentence tokenization--------------------------')
184
+ DEBUG && console.log('---Replacement map---------------------------------------')
185
+ DEBUG && console.log([...this.replacementMap.entries()])
186
+ DEBUG && console.log('---Delimiter map-----------------------------------------')
187
+ DEBUG && console.log([...this.delimiterMap.entries()])
188
+ DEBUG && console.log('---------------------------------------------------------')
46
189
 
47
- return this.trim(tokens)
190
+ return trimmedSentences2
48
191
  }
49
192
  }
50
193
 
@@ -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
 
@@ -19,7 +19,8 @@ const knownAbbreviations = [
19
19
  'tel.',
20
20
  'temp.',
21
21
  'vet.',
22
- 'vs.'
22
+ 'vs.',
23
+ 'i.e.'
23
24
  ]
24
25
 
25
26
  exports.knownAbbreviations = knownAbbreviations
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.0",
5
5
  "homepage": "https://github.com/NaturalNode/natural",
6
6
  "repository": {
7
7
  "type": "git",