├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── lib ├── index.js └── tokens.js ├── package.json └── test ├── filter.js ├── flow.js ├── instance.js ├── merge.js ├── re.js ├── sections.js ├── tokenize.js └── tokens.js /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | 5 | # Runtime data 6 | pids 7 | *.pid 8 | *.seed 9 | 10 | # Directory for instrumented libs generated by jscoverage/JSCover 11 | lib-cov 12 | 13 | # Coverage directory used by tools like istanbul 14 | coverage 15 | 16 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 17 | .grunt 18 | 19 | # node-waf configuration 20 | .lock-wscript 21 | 22 | # Compiled binary addons (http://nodejs.org/api/addons.html) 23 | build/Release 24 | 25 | # Dependency directory 26 | # https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git 27 | node_modules 28 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - "4.1" 4 | - "0.11" 5 | - "0.10" 6 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # tokenize-text 2 | 3 | [![Build Status](https://travis-ci.org/GitbookIO/tokenize-text.png?branch=master)](https://travis-ci.org/GitbookIO/tokenize-text) 4 | [![NPM version](https://badge.fury.io/js/tokenize-text.svg)](http://badge.fury.io/js/tokenize-text) 5 | 6 | Javascript text tokenizer that is easy to use and compose. 7 | 8 | ### Installation 9 | 10 | ``` 11 | $ npm install tokenize-text 12 | ``` 13 | 14 | ### Usage 15 | 16 | ```js 17 | var Tokenizer = require('tokenize-text'); 18 | var tokenize = new Tokenizer(); 19 | ``` 20 | 21 | #### tokenize.split(fn) 22 | 23 | This is the main method of this module, all other methods are using it. 24 | 25 | `fn` will be called with 4 arguments: 26 | 27 | - `text`: text value of the token (`text == currentToken.value`) 28 | - `currentToken`: current token object 29 | - `prevToken`: precedent token (or null) 30 | - `nextToken`: next token (or null) 31 | 32 | `fn` should return a string, an array of string, a token or an array of tokens. 33 | 34 | `tokenize.split(fn)` returns a tokenizer function that accept a list of tokens or a string argument (it will be convert as one token). 35 | 36 | The tokenizer function returns an array of tokens with the following properties: 37 | 38 | - `value`: text content of the token 39 | - `index`: absolute position in the original text 40 | - `offset`: length of the token (equivalent to `value.length`) 41 | 42 | ```js 43 | // Simple tokenizer that split into 2 sections 44 | var splitIn2 = tokenize.split(function(text, currentToken, prevToken, nextToken) { 45 | return [ 46 | text.slice(0, text.length / 2), 47 | text.slice(text.length / 2) 48 | ] 49 | }); 50 | 51 | var tokens = splitIn2('hello'); 52 | 53 | /* 54 | [ 55 | { value: 'he', index: 0, offset: 2 }, 56 | { value: 'llo', index: 2, offset: 3 } 57 | ] 58 | */ 59 | ``` 60 | 61 | #### tokenize.re(re) 62 | 63 | Tokenize using a regular expression: 64 | 65 | ```js 66 | var extractUppercase = tokenize.re(/[A-Z]/); 67 | var tokens = extractUppercase('aBcD'); 68 | 69 | /* 70 | [ 71 | { value: 'B', index: 1, offset: 1 }, 72 | { value: 'D', index: 3, offset: 1 } 73 | ] 74 | */ 75 | ``` 76 | 77 | #### tokenize.characters() 78 | 79 | Tokenize and split as characters, `tokenize.characters()` is equivalent to `tokenize.re(/[^\s]/)`. 80 | 81 | ```js 82 | var tokens = tokenize.characters()('abc'); 83 | 84 | /* 85 | [ 86 | { value: 'a', index: 0, offset: 1 }, 87 | { value: 'b', index: 1, offset: 1 }, 88 | { value: 'c', index: 2, offset: 1 } 89 | ] 90 | */ 91 | ``` 92 | 93 | #### tokenize.sections() 94 | 95 | Split in sections, sections are split by `\n . , ; ! ?`. 96 | 97 | ```js 98 | var tokens = tokenize.sections()('this is sentence 1. this is sentence 2'); 99 | 100 | /* 101 | [ 102 | { 103 | value: 'this is sentence 1', 104 | index: 0, 105 | offset: 18 106 | }, 107 | { 108 | value: ' this is sentence 2', 109 | index: 19, 110 | offset: 19 111 | } 112 | ] 113 | */ 114 | ``` 115 | 116 | #### tokenize.words() 117 | 118 | Split in words: 119 | 120 | ```js 121 | var tokens = tokenize.words()('hello, how are you?'); 122 | 123 | /* 124 | [ 125 | { value: 'hello', index: 0, offset: 5 }, 126 | { value: 'how', index: 7, offset: 3 }, 127 | { value: 'are', index: 11, offset: 3 }, 128 | { value: 'you', index: 15, offset: 3 } 129 | ] 130 | */ 131 | ``` 132 | 133 | #### tokenize.filter(fn) 134 | 135 | Filter the list of tokens by calling `fn(token)`: 136 | 137 | ```js 138 | // Filter the words to extract the ones that start with an uppercase 139 | var extractNames = tokenize.filter(function(word, current, prev) { 140 | return (prev && /[A-Z]/.test(word[0])); 141 | }); 142 | 143 | // Split texts in words 144 | var words = tokenize.words()('My name is Samy.'); 145 | 146 | // Apply the filter 147 | var tokens = extractNames(words); 148 | 149 | /* 150 | [ 151 | { value: 'Samy', index: 11, offset: 4 } 152 | ] 153 | */ 154 | ``` 155 | 156 | #### tokenize.flow(fn1, fn2, [...]) 157 | 158 | Creates a tokenizer that returns the result of invoking the provided tokenizers for each input token. 159 | 160 | ```js 161 | var extractNames = tokenize.flow( 162 | // Split text as words 163 | tokenize.words(), 164 | 165 | // Filter the words to extract the ones that start with an uppercase 166 | tokenize.filter(function(word, current, prev) { 167 | return (prev && /[A-Z]/.test(word[0])); 168 | }) 169 | ); 170 | 171 | var tokens = extractNames('My name is Samy.'); 172 | ``` 173 | 174 | To execute all tokenizer in series, you can use `tokenize.serie(fn1, fn2, [...])` instead. 175 | 176 | ### Examples 177 | 178 | #### Extract repeated words in sentences 179 | 180 | Example to extract all repeated words in sentences: 181 | 182 | ```js 183 | var repeatedWords = tokenize.flow( 184 | // Tokenize as sections 185 | tokenize.sections(), 186 | 187 | // For each sentence 188 | tokenize.flow( 189 | // Tokenize as words 190 | tokenize.words(), 191 | 192 | // Filter words to extract only repeated ones 193 | tokenize.filter(function(word, token, prev) { 194 | return ( 195 | prev && 196 | token.value.toLowerCase() === prev.value.toLowerCase() 197 | ); 198 | }) 199 | ) 200 | ); 201 | 202 | 203 | var tokens = repeatedWords('This is great great. Great is an an awesome words'); 204 | 205 | /* 206 | [ 207 | { value: 'great', index: 14, offset: 5 }, 208 | { value: 'an', index: 33, offset: 2 } 209 | ] 210 | */ 211 | ``` 212 | 213 | 214 | -------------------------------------------------------------------------------- /lib/index.js: -------------------------------------------------------------------------------- 1 | var _ = require("lodash"); 2 | 3 | var tokenUtils = require('./tokens'); 4 | 5 | var WORD_BOUNDARY_CHARS = '\t\r\n\u00A0 !\"#$%&()*+,\-.\\/:;<=>?@\[\\\]^_`{|}~'; 6 | var WORD_BOUNDARY_REGEX = new RegExp('[' + WORD_BOUNDARY_CHARS + ']'); 7 | var SPLIT_REGEX = new RegExp( 8 | '([^' + WORD_BOUNDARY_CHARS + ']+)'); 9 | 10 | function Tokenizer(opts) { 11 | if (!(this instanceof Tokenizer)) return (new Tokenizer(opts)); 12 | 13 | this.opts = _.defaults(opts || {}, { 14 | cacheGet: function(key) { return null; }, 15 | cacheSet: function(key, value) { } 16 | }); 17 | 18 | _.bindAll(this); 19 | } 20 | 21 | // Tokenize a text using a transformative function 22 | Tokenizer.prototype.split = function tokenizeSplit(fn, opts) { 23 | var that = this; 24 | 25 | opts = _.defaults(opts || {}, { 26 | preserveProperties: true, 27 | cache: _.constant(null) 28 | }); 29 | 30 | return function(text, tok) { 31 | // If called as a split function, directly call fn 32 | if (arguments.length == 6) return fn.apply(null, arguments); 33 | 34 | var prev = undefined; 35 | var cacheId, cacheValue; 36 | 37 | // if string, convert to one large token 38 | if (_.isString(text)) { 39 | text = [ 40 | { 41 | value: text, 42 | index: 0, 43 | offset: text.length 44 | } 45 | ]; 46 | } else if (!_.isArray(text)) { 47 | text = [text]; 48 | } 49 | 50 | cacheId = tokenUtils.tokensId(text, opts.cache()); 51 | if (cacheId) { 52 | cacheValue = that.opts.cacheGet(cacheId); 53 | if (cacheValue) { 54 | return cacheValue; 55 | } 56 | } 57 | 58 | return _.chain(text) 59 | .map(function(token, i) { 60 | var next = text[i + 1]; 61 | var tokens = fn( 62 | // Current text value 63 | token.value, 64 | 65 | // Current complete token 66 | _.clone(token), 67 | 68 | // Previous token 69 | prev? _.clone(prev) : null, 70 | 71 | // Next token 72 | next? _.clone(next) : null, 73 | 74 | // Index in the tokens list 75 | i, 76 | 77 | // List of all tokens 78 | text 79 | ) || []; 80 | 81 | // Normalize tokens and return 82 | tokens = tokenUtils.normalize(token, tokens); 83 | 84 | // Preserve properties 85 | if (opts.preserveProperties) { 86 | var props = tokenUtils.properties(token); 87 | tokens = _.map(tokens, function(_tok) { 88 | return _.defaults(_tok, props); 89 | }); 90 | } 91 | 92 | // Update reference to prev 93 | prev = token; 94 | 95 | return tokens; 96 | }) 97 | .compact() 98 | .flatten() 99 | .tap(function(_tokens) { 100 | if (!cacheId) return; 101 | 102 | that.opts.cacheSet(cacheId, _tokens); 103 | }) 104 | .value(); 105 | }; 106 | }; 107 | 108 | // Debug a tokenizing flow 109 | Tokenizer.prototype.debug = function tokenizeDebug(prefix) { 110 | return this.filter(function(text, tok) { 111 | var props = tokenUtils.properties(tok); 112 | 113 | console.log( 114 | prefix || '', 115 | '[' + tok.index + '-' + (tok.index + tok.offset) + ']', 116 | JSON.stringify(tok.value), 117 | _.size(props)? JSON.stringify(props) : '' 118 | ); 119 | return true; 120 | }); 121 | }; 122 | 123 | 124 | // Tokenize a text using a RegExp 125 | Tokenizer.prototype.re = function tokenizeRe(re, opts) { 126 | opts = _.defaults(opts || {}, { 127 | split: false 128 | }); 129 | 130 | return this.split(function(text, tok) { 131 | var originalText = text; 132 | var tokens = []; 133 | var match; 134 | var start = 0; 135 | var lastIndex = 0; 136 | 137 | while (match = re.exec(text)) { 138 | // Index in the current text section 139 | var index = match.index; 140 | 141 | // Index in the original text 142 | var absoluteIndex = start + index; 143 | 144 | var value = match[0] || ""; 145 | var offset = value.length; 146 | 147 | // If splitting, push missed text 148 | if (opts.split && start < absoluteIndex) { 149 | var beforeText = originalText.slice(start, absoluteIndex); 150 | tokens.push({ 151 | value: beforeText, 152 | index: start, 153 | offset: beforeText.length 154 | }); 155 | } 156 | 157 | tokens.push({ 158 | value: value, 159 | index: absoluteIndex, 160 | offset: offset, 161 | match: match 162 | }); 163 | 164 | text = text.slice(index + offset); 165 | start = absoluteIndex + offset; 166 | } 167 | 168 | // If splitting, push left text 169 | if (opts.split && text) { 170 | tokens.push({ 171 | value: text, 172 | index: start, 173 | offset: text.length 174 | }); 175 | } 176 | 177 | return tokens; 178 | }, { 179 | cache: function() { 180 | return re.toString(); 181 | } 182 | }); 183 | }; 184 | 185 | // Split and merge tokens 186 | // Used to split as sentences even if sentences is separated in multiple tokens (ex: markup) 187 | // if fn results contain a 'null', it will split in two tokens 188 | Tokenizer.prototype.splitAndMerge = function tokenizeSplitAndMerge(fn, opts) { 189 | var that = this; 190 | 191 | opts = _.defaults(opts || {}, { 192 | mergeWith: '' 193 | }); 194 | 195 | return function(tokens) { 196 | var result = []; 197 | var accu = []; 198 | 199 | function pushAccu() { 200 | if (accu.length == 0) return; 201 | 202 | // Merge accumulator into one token 203 | var tok = tokenUtils.merge(accu, opts.mergeWith); 204 | 205 | result.push(tok); 206 | accu = []; 207 | } 208 | 209 | that.split(function(word, token) { 210 | var toks = fn.apply(null, arguments); 211 | 212 | // Normalize tokens 213 | toks = tokenUtils.normalize(token, toks); 214 | 215 | // Accumulate tokens and push to final results 216 | _.each(toks, function(tok) { 217 | if (tok === null) { 218 | pushAccu(); 219 | } else { 220 | accu.push(tok); 221 | } 222 | }); 223 | })(tokens); 224 | 225 | // Push tokens left in accumulator 226 | pushAccu(); 227 | 228 | return result; 229 | }; 230 | }; 231 | 232 | // Filter when tokenising 233 | Tokenizer.prototype.filter = function tokenizeFilter(fn) { 234 | return this.split(function(text, tok) { 235 | if (fn.apply(null, arguments)) { 236 | return { 237 | value: tok.value, 238 | index: 0, 239 | offset: tok.offset 240 | }; 241 | } 242 | return undefined; 243 | }); 244 | }; 245 | 246 | // Extend a token properties 247 | Tokenizer.prototype.extend = function tokenizeExtend(fn) { 248 | return this.split(function(text, tok) { 249 | var o = _.isFunction(fn)? fn.apply(null, arguments) : fn; 250 | 251 | return _.extend({ 252 | value: tok.value, 253 | index: 0, 254 | offset: tok.offset 255 | }, o); 256 | }); 257 | }; 258 | 259 | // Condition for tokenizing flow 260 | // "fns" will be called if condition passed 261 | Tokenizer.prototype.ifthen = function(condition, then) { 262 | //var fns = _.toArray(arguments).slice(1); 263 | //var flow = this.flow.apply(this, fns); 264 | 265 | return this.split(function(text, tok) { 266 | if (condition.apply(null, arguments)) { 267 | return then.apply(null, arguments); 268 | } 269 | 270 | return _.omit(tok, 'index'); 271 | }); 272 | }; 273 | 274 | // Filter by testing a regex 275 | Tokenizer.prototype.test = function tokenizeTest(re) { 276 | return this.filter(function(text, tok) { 277 | return re.test(text); 278 | }, { 279 | cache: re.toString() 280 | }); 281 | }; 282 | 283 | // Process token by all arguments 284 | Tokenizer.prototype.flow = function tokenizeFlow() { 285 | var fn = _.flow.apply(_, arguments); 286 | return this.split(fn); 287 | }; 288 | 289 | // Group and process a token as a group 290 | Tokenizer.prototype.serie = function tokenizeFlow() { 291 | var fn = _.flow.apply(_, arguments); 292 | return fn; 293 | }; 294 | 295 | 296 | // Merge all tokens into one 297 | Tokenizer.prototype.merge = _.partial(Tokenizer.prototype.splitAndMerge, _.identity); 298 | 299 | 300 | Tokenizer.prototype.sections = _.partial(Tokenizer.prototype.re, /([^\n\.,;!?]+)/i, { split: false }); 301 | Tokenizer.prototype.words = _.partial(Tokenizer.prototype.re, SPLIT_REGEX); 302 | Tokenizer.prototype.characters = _.partial(Tokenizer.prototype.re, /[^\s]/); 303 | 304 | module.exports = Tokenizer; 305 | -------------------------------------------------------------------------------- /lib/tokens.js: -------------------------------------------------------------------------------- 1 | var _ = require("lodash"); 2 | 3 | /* 4 | Token is an object like: 5 | 6 | { 7 | "value": "text content", 8 | 9 | // Position of the index 10 | "index": 0, 11 | 12 | // Length of the token 13 | "offset": "text content".length 14 | } 15 | */ 16 | 17 | // Return a string ID to represent a list of tokens 18 | function tokensId(tokens, prepend) { 19 | if (!prepend) return null; 20 | 21 | return _.reduce(tokens, function(prev, token) { 22 | var tokId = [ 23 | token.index, 24 | token.offset, 25 | token.value 26 | ].join('-'); 27 | 28 | return [prev, tokId].join(':'); 29 | }, prepend); 30 | } 31 | 32 | // Return properties for a token 33 | function tokenProperties(tok) { 34 | return _.omit(tok, ['index', 'offset', 'value']); 35 | } 36 | 37 | // Normalize and resolve a list of tokens relative to a token 38 | function normalizeTokens(relative, tokens) { 39 | var _index = 0; 40 | 41 | // Force as an array 42 | if (!_.isArray(tokens)) tokens = [tokens]; 43 | 44 | return _.map(tokens, function(subtoken) { 45 | if (_.isNull(subtoken)) return null; 46 | if (_.isString(subtoken)) { 47 | subtoken = { 48 | value: subtoken, 49 | index: _index, 50 | offset: subtoken.length 51 | }; 52 | } 53 | 54 | if (_.isObject(subtoken)) { 55 | subtoken.index = subtoken.index || 0; 56 | _index = _index + subtoken.index + subtoken.offset; 57 | 58 | // Transform as an absolute token 59 | subtoken.index = relative.index + subtoken.index; 60 | subtoken.offset = subtoken.offset || subtoken.value.length; 61 | } 62 | 63 | return subtoken; 64 | }); 65 | } 66 | 67 | // Merge tokens 68 | function mergeTokens(tokens, mergeWith) { 69 | if (tokens.length == 0) return null; 70 | 71 | var value = ''; 72 | var offset = 0; 73 | 74 | var firstIndex = _.first(tokens).index; 75 | 76 | _.each(tokens, function(token, i) { 77 | var prev = tokens[i - 1]; 78 | var next = tokens[i + 1]; 79 | 80 | var toFill = prev? (token.index + 1 - (prev.index + prev.offset)): 0; 81 | value = value + new Array(toFill).join(mergeWith) + token.value; 82 | 83 | var absoluteOffset = (token.index - firstIndex) + token.offset; 84 | if (absoluteOffset > offset) offset = absoluteOffset; 85 | }); 86 | 87 | return { 88 | // Index equal is the one from the first token 89 | index: firstIndex, 90 | 91 | value: value, 92 | offset: Math.max(offset, value.length) 93 | } 94 | } 95 | 96 | module.exports = { 97 | tokensId: tokensId, 98 | normalize: normalizeTokens, 99 | properties: tokenProperties, 100 | merge: mergeTokens 101 | }; 102 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "tokenize-text", 3 | "version": "1.1.3", 4 | "homepage": "https://github.com/GitbookIO/tokenize-text", 5 | "description": "Javascript text tokenizer that is easy to use and compose", 6 | "main": "lib/index.js", 7 | "dependencies": { 8 | "lodash": "^3.2.0" 9 | }, 10 | "devDependencies": { 11 | "mocha": "2.3.3", 12 | "should": "7.1.0" 13 | }, 14 | "scripts": { 15 | "test": "mocha --reporter spec --recursive --bail" 16 | }, 17 | "repository": { 18 | "type": "git", 19 | "url": "https://github.com/GitbookIO/tokenize-text.git" 20 | }, 21 | "author": "GitBook ", 22 | "license": "Apache-2.0", 23 | "bugs": { 24 | "url": "https://github.com/GitbookIO/tokenize-text/issues" 25 | } 26 | } -------------------------------------------------------------------------------- /test/filter.js: -------------------------------------------------------------------------------- 1 | var tokenize = require("./instance"); 2 | 3 | describe('tokenize.filter()', function() { 4 | it('should correctly pass prev token', function() { 5 | var extractName = tokenize.filter(function(word, current, prev) { 6 | return (prev && /[A-Z]/.test(word[0])); 7 | }); 8 | 9 | var words = tokenize.words()('My name is Samy.'); 10 | var tokens = extractName(words); 11 | 12 | tokens.should.have.lengthOf(1); 13 | tokens[0].value.should.equal('Samy'); 14 | tokens[0].index.should.equal(11); 15 | tokens[0].offset.should.equal(4); 16 | }); 17 | 18 | it('should not change valeu of index and offset', function() { 19 | var tokens = [ 20 | { value: 'test', index: 10, offset: 10 }, 21 | { value: 'test 2', index: 30, offset: 20} 22 | ]; 23 | 24 | var filter = tokenize.filter(function() { 25 | return true; 26 | }); 27 | 28 | tokens = filter(tokens); 29 | tokens.should.have.lengthOf(2); 30 | tokens[0].index.should.equal(10); 31 | tokens[0].offset.should.equal(10); 32 | tokens[1].index.should.equal(30); 33 | tokens[1].offset.should.equal(20); 34 | }) 35 | }); 36 | 37 | -------------------------------------------------------------------------------- /test/flow.js: -------------------------------------------------------------------------------- 1 | var tokenize = require("./instance"); 2 | 3 | describe('tokenize.flow()', function() { 4 | 5 | it('ex: repeated words', function() { 6 | var repeatedWords = tokenize.flow( 7 | // Tokenize as sections 8 | tokenize.sections(), 9 | 10 | // For each sentence 11 | tokenize.flow( 12 | // Tokenize as words 13 | tokenize.words(), 14 | 15 | // For each sentences 16 | tokenize.filter(function(word, token, prev) { 17 | return ( 18 | prev && 19 | token.value.toLowerCase() === prev.value.toLowerCase() 20 | ); 21 | }) 22 | ) 23 | ); 24 | 25 | 26 | var tokens = repeatedWords('This is great great. Great is an an awesome words'); 27 | tokens.should.have.lengthOf(2); 28 | 29 | tokens[0].value.should.equal('great'); 30 | tokens[0].index.should.equal(14); 31 | tokens[0].offset.should.equal(5); 32 | 33 | tokens[1].value.should.equal('an'); 34 | tokens[1].index.should.equal(33); 35 | tokens[1].offset.should.equal(2); 36 | }); 37 | }); 38 | 39 | -------------------------------------------------------------------------------- /test/instance.js: -------------------------------------------------------------------------------- 1 | var should = require('should'); 2 | var Tokenizer = require("../lib"); 3 | 4 | module.exports = new Tokenizer(); 5 | -------------------------------------------------------------------------------- /test/merge.js: -------------------------------------------------------------------------------- 1 | var tokenize = require("./instance"); 2 | 3 | describe('tokenize.splitAndMerge(fn)', function() { 4 | it('should merge according to a criteria', function() { 5 | var tokens = tokenize.flow( 6 | tokenize.characters(), 7 | tokenize.splitAndMerge(function(tok) { 8 | if (tok == '.') return [tok, null]; 9 | return tok; 10 | }) 11 | )('ab.c'); 12 | 13 | tokens.should.have.lengthOf(2); 14 | tokens[0].value.should.equal('ab.'); 15 | tokens[0].index.should.equal(0); 16 | tokens[0].offset.should.equal(3); 17 | 18 | tokens[1].value.should.equal('c'); 19 | tokens[1].index.should.equal(3); 20 | tokens[1].offset.should.equal(1); 21 | }); 22 | 23 | it('should handle disperse tokens', function() { 24 | var tokens = tokenize.flow( 25 | tokenize.re(/\S+/), 26 | tokenize.splitAndMerge(function(tok) { 27 | if (tok == '|') return null; 28 | return tok; 29 | }, { 30 | mergeWith: ' ' 31 | }) 32 | )('ab cd | ef gh'); 33 | 34 | tokens.should.have.lengthOf(2); 35 | 36 | tokens[0].value.should.equal('ab cd'); 37 | tokens[0].index.should.equal(0); 38 | tokens[0].offset.should.equal(5); 39 | 40 | tokens[1].value.should.equal('ef gh'); 41 | tokens[1].index.should.equal(8); 42 | tokens[1].offset.should.equal(5); 43 | }); 44 | 45 | it('should correctly calcul offset', function() { 46 | var tokens = tokenize.flow( 47 | tokenize.re(/\S+/), 48 | tokenize.splitAndMerge(function(tok) { 49 | if (tok == '|') return null; 50 | return tok; 51 | }, { 52 | mergeWith: '' 53 | }) 54 | )('ab cd | ef gh'); 55 | 56 | tokens.should.have.lengthOf(2); 57 | 58 | tokens[0].value.should.equal('abcd'); 59 | tokens[0].index.should.equal(0); 60 | tokens[0].offset.should.equal(5); 61 | 62 | tokens[1].value.should.equal('efgh'); 63 | tokens[1].index.should.equal(8); 64 | tokens[1].offset.should.equal(5); 65 | }); 66 | 67 | it('should handle splitting in the middle of tokens', function() { 68 | var tokens = tokenize.flow( 69 | tokenize.words(), 70 | tokenize.splitAndMerge(function(tok) { 71 | return [ 72 | tok.slice(0, tok.length/2), 73 | null, 74 | tok.slice(tok.length/2) 75 | ] 76 | }) 77 | )('tata dada'); 78 | 79 | tokens.should.have.lengthOf(3); 80 | tokens[0].value.should.equal('ta'); 81 | tokens[1].value.should.equal('tada'); 82 | tokens[2].value.should.equal('da'); 83 | }); 84 | }); 85 | 86 | -------------------------------------------------------------------------------- /test/re.js: -------------------------------------------------------------------------------- 1 | var tokenize = require("./instance"); 2 | 3 | describe('tokenize.re()', function() { 4 | 5 | it('should correctly extract using a regex', function() { 6 | var extractUppercase = tokenize.re(/[A-Z]/); 7 | var tokens = extractUppercase('aBcD'); 8 | 9 | tokens.should.have.lengthOf(2); 10 | tokens[0].value.should.equal('B'); 11 | tokens[0].index.should.equal(1); 12 | tokens[1].value.should.equal('D'); 13 | tokens[1].index.should.equal(3); 14 | }); 15 | 16 | it('should accept option to split instead of extracting', function() { 17 | var extract = tokenize.re(/\ /i, { split: true }); 18 | var tokens = extract('hello world'); 19 | 20 | tokens.should.have.lengthOf(3); 21 | tokens[0].value.should.equal('hello'); 22 | tokens[0].index.should.equal(0); 23 | tokens[0].offset.should.equal(5); 24 | 25 | tokens[1].value.should.equal(' '); 26 | tokens[1].index.should.equal(5); 27 | tokens[1].offset.should.equal(1); 28 | 29 | tokens[2].value.should.equal('world'); 30 | tokens[2].index.should.equal(6); 31 | tokens[2].offset.should.equal(5); 32 | }); 33 | 34 | it('should accept option to split instead of extracting (2)', function() { 35 | var extract = tokenize.re(/\s/i, { split: true }); 36 | var tokens = extract('hello world\ntest'); 37 | 38 | tokens.should.have.lengthOf(5); 39 | tokens[0].value.should.equal('hello'); 40 | tokens[1].value.should.equal(' '); 41 | tokens[2].value.should.equal('world'); 42 | tokens[3].value.should.equal('\n'); 43 | tokens[4].value.should.equal('test'); 44 | }); 45 | }); 46 | 47 | -------------------------------------------------------------------------------- /test/sections.js: -------------------------------------------------------------------------------- 1 | var tokenize = require("./instance"); 2 | 3 | describe('tokenize.sections()', function() { 4 | it('should split by .', function() { 5 | var tokens = tokenize.sections()('this is sentence 1. this is sentence 2'); 6 | tokens.should.have.lengthOf(2); 7 | 8 | tokens[0].value.should.equal('this is sentence 1'); 9 | tokens[0].index.should.equal(0); 10 | tokens[0].offset.should.equal(18); 11 | 12 | tokens[1].value.should.equal(' this is sentence 2'); 13 | tokens[1].index.should.equal(19); 14 | tokens[1].offset.should.equal(19); 15 | }); 16 | }); 17 | 18 | -------------------------------------------------------------------------------- /test/tokenize.js: -------------------------------------------------------------------------------- 1 | var tokenize = require("./instance"); 2 | 3 | describe('Tokenizer', function() { 4 | it('tokenize.split()', function() { 5 | var splitIn2 = tokenize.split(function(text, currentToken, prevToken, nextToken) { 6 | return [ 7 | text.slice(0, text.length / 2), 8 | text.slice(text.length / 2) 9 | ] 10 | }); 11 | 12 | var tokens = splitIn2('hello'); 13 | 14 | tokens.should.have.lengthOf(2); 15 | tokens[0].value.should.equal('he'); 16 | tokens[0].index.should.equal(0); 17 | tokens[0].offset.should.equal(2); 18 | tokens[1].value.should.equal('llo'); 19 | tokens[1].index.should.equal(2); 20 | tokens[1].offset.should.equal(3); 21 | }); 22 | 23 | it('tokenize.characters()', function() { 24 | var tokens = tokenize.characters()('abc'); 25 | 26 | tokens.should.have.lengthOf(3); 27 | tokens[0].value.should.equal('a'); 28 | tokens[0].index.should.equal(0); 29 | tokens[1].value.should.equal('b'); 30 | tokens[1].index.should.equal(1); 31 | tokens[2].value.should.equal('c'); 32 | tokens[2].index.should.equal(2); 33 | }); 34 | 35 | it('tokenize.words()', function() { 36 | var tokens = tokenize.words()('a b c'); 37 | 38 | tokens.should.have.lengthOf(3); 39 | tokens[0].value.should.equal('a'); 40 | tokens[0].index.should.equal(0); 41 | tokens[1].value.should.equal('b'); 42 | tokens[1].index.should.equal(2); 43 | tokens[2].value.should.equal('c'); 44 | tokens[2].index.should.equal(4); 45 | }); 46 | 47 | it('tokenize.splitAndMerge(fn)', function() { 48 | var tokens = tokenize.flow( 49 | tokenize.characters(), 50 | tokenize.splitAndMerge(function(tok) { 51 | if (tok == '.') return [tok, null]; 52 | return tok; 53 | }) 54 | )('ab.c'); 55 | 56 | tokens.should.have.lengthOf(2); 57 | tokens[0].value.should.equal('ab.'); 58 | tokens[0].index.should.equal(0); 59 | tokens[0].offset.should.equal(3); 60 | 61 | tokens[1].value.should.equal('c'); 62 | tokens[1].index.should.equal(3); 63 | tokens[1].offset.should.equal(1); 64 | }); 65 | }); 66 | 67 | -------------------------------------------------------------------------------- /test/tokens.js: -------------------------------------------------------------------------------- 1 | var tokenUtils = require('../lib/tokens'); 2 | 3 | describe('Tokens Utilities', function() { 4 | describe('tokensUtils.normalize()', function() { 5 | it('should correctly normalize', function() { 6 | var tokens = tokenUtils.normalize({ 7 | value: 'test hello', 8 | index: 5 9 | }, [ 10 | { 11 | value: 'test', 12 | index: 0, 13 | offset: 4 14 | }, 15 | { 16 | value: 'hello', 17 | index: 5, 18 | offset: 5 19 | } 20 | ]); 21 | 22 | tokens.should.have.lengthOf(2); 23 | tokens[0].value.should.equal('test'); 24 | tokens[0].index.should.equal(5); 25 | 26 | tokens[1].value.should.equal('hello'); 27 | tokens[1].index.should.equal(10); 28 | }); 29 | 30 | it('should correctly ignore nulls', function() { 31 | var tokens = tokenUtils.normalize({ 32 | value: 'test hello', 33 | index: 5 34 | }, [ 35 | { 36 | value: 'test', 37 | index: 0, 38 | offset: 4 39 | }, 40 | null, 41 | { 42 | value: 'hello', 43 | index: 5, 44 | offset: 5 45 | } 46 | ]); 47 | 48 | tokens.should.have.lengthOf(3); 49 | tokens[0].value.should.equal('test'); 50 | tokens[0].index.should.equal(5); 51 | 52 | tokens[2].value.should.equal('hello'); 53 | tokens[2].index.should.equal(10); 54 | }); 55 | 56 | it('should handle texts and ignore nulls', function() { 57 | var tokens = tokenUtils.normalize({ 58 | value: 'Barney.The', 59 | index: 6, 60 | offset: 10 61 | }, [ 'Barney', null, 'The' ]); 62 | 63 | tokens.should.have.lengthOf(3); 64 | tokens[0].value.should.equal('Barney'); 65 | tokens[0].index.should.equal(6); 66 | tokens[2].value.should.equal('The'); 67 | tokens[2].index.should.equal(12); 68 | }); 69 | }); 70 | }); 71 | 72 | --------------------------------------------------------------------------------