@mark1russell7/text 0.0.13 → 0.0.14
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.
- package/README.md +16 -0
- package/build/index.d.ts +3 -29
- package/build/index.d.ts.map +1 -1
- package/build/index.js +1 -40
- package/build/index.js.map +1 -1
- package/build/search.d.ts +113 -0
- package/build/search.d.ts.map +1 -0
- package/build/search.js +150 -0
- package/build/search.js.map +1 -0
- package/package.json +6 -2
- package/src/index.ts +1 -0
- package/src/search.ts +137 -0
package/README.md
CHANGED
|
@@ -66,6 +66,22 @@ wordSearch("istanbul")("İSTANBUL"); // false: "İ" keeps its dot as U+0307
|
|
|
66
66
|
searchKey("file"); // "file"
|
|
67
67
|
```
|
|
68
68
|
|
|
69
|
+
### A ranked search
|
|
70
|
+
|
|
71
|
+
The entry `@mark1russell7/text/search` also ranks the documents of a corpus for a query with TF-IDF and the cosine similarity. Each function is pure and has no I/O.
|
|
72
|
+
|
|
73
|
+
- `searchWords(text, options)` gives the search keys of the words of a text (Unicode Standard Annex 29). The options remove stop words, refuse words and change words.
|
|
74
|
+
- `inverseDocumentFrequency(documents, form)` gives the IDF of each term. The form `plain` is ln(N / df), so a term in each document has the weight 0. The form `smooth` is ln((N + 1) / (df + 1)) + 1.
|
|
75
|
+
- `termVector(words, idf)` gives the weights (1 + ln(tf)) × idf with a length of 1. `cosineSimilarity(a, b)` compares two vectors.
|
|
76
|
+
- `rankDocuments(corpus, query, form)` gives the score of each document, best first. A tie keeps the order of the corpus.
|
|
77
|
+
|
|
78
|
+
```ts
|
|
79
|
+
import { rankDocuments, searchWords } from "@mark1russell7/text/search";
|
|
80
|
+
|
|
81
|
+
const corpus = ["The release gate", "The topic graph of the site", "A graph page"].map((text) => searchWords(text));
|
|
82
|
+
rankDocuments(corpus, searchWords("topic graph")); // [{ index: 1, … }, { index: 2, … }, { index: 0, score: 0 }]
|
|
83
|
+
```
|
|
84
|
+
|
|
69
85
|
## The order of texts
|
|
70
86
|
|
|
71
87
|
The entry `@mark1russell7/text/order` has two orders of texts. Each order is the same in each locale and in each copy of a program. The name of each function tells its unit.
|
package/build/index.d.ts
CHANGED
|
@@ -3,8 +3,10 @@
|
|
|
3
3
|
* expressions, Markdown and GitHub Actions workflow commands. The other groups are the English word forms, a word
|
|
4
4
|
* search and the text of a thrown value. The entry `@mark1russell7/text/redact` removes secrets from a text, and the entry
|
|
5
5
|
* `@mark1russell7/text/order` has two orders of texts. The entry `@mark1russell7/text/english` adds the list join `listOf`.
|
|
6
|
+
* The entry `@mark1russell7/text/search` adds a ranked search with TF-IDF.
|
|
6
7
|
*/
|
|
7
8
|
import { countOf } from "./english.js";
|
|
9
|
+
import { searchKey, wordSearch } from "./search.js";
|
|
8
10
|
/**
|
|
9
11
|
* This module has the text of a thrown value.
|
|
10
12
|
*/
|
|
@@ -76,33 +78,5 @@ export declare function escapeWorkflowData(text: string): string;
|
|
|
76
78
|
* @returns The property value. The runner decodes it to the text.
|
|
77
79
|
*/
|
|
78
80
|
export declare function escapeWorkflowProperty(text: string): string;
|
|
79
|
-
|
|
80
|
-
* This function gives the search key of a text. `wordSearch` compares the keys of texts. The function does these steps:
|
|
81
|
-
*
|
|
82
|
-
* 1. It applies the Unicode normalization NFKC. Thus the ligature "fi" agrees with "fi", and full-width letters agree
|
|
83
|
-
* with ASCII letters.
|
|
84
|
-
* 2. It applies the full lower case, then the full upper case, then the full lower case. Thus "ß", "ẞ" and "SS" give
|
|
85
|
-
* "ss".
|
|
86
|
-
* 3. It changes the small final sigma "ς" to "σ", as Unicode case folding does.
|
|
87
|
-
* 4. It applies NFKC again.
|
|
88
|
-
*
|
|
89
|
-
* The steps use no rules of a locale. Thus the Turkish "İ" gives "i" with a combining dot above (U+0307), and the
|
|
90
|
-
* Turkish "ı" gives "i". The key of a key is the same key. Accents stay, so "é" does not agree with "e".
|
|
91
|
-
*
|
|
92
|
-
* @param text - The plain text.
|
|
93
|
-
* @returns The search key of the text.
|
|
94
|
-
*/
|
|
95
|
-
export declare function searchKey(text: string): string;
|
|
96
|
-
/**
|
|
97
|
-
* This function gives the test of a search. The function makes the key of the search with `searchKey`. Then it splits
|
|
98
|
-
* the key into words at each run of white space, the class `\s` of a regular expression.
|
|
99
|
-
*
|
|
100
|
-
* The test tells if the key of a text contains each word, in any order. A word can be a part of a longer word, so the
|
|
101
|
-
* search "art" finds "Party". A search with no words agrees with each text.
|
|
102
|
-
*
|
|
103
|
-
* @param query - The search, as a person types it.
|
|
104
|
-
* @returns The test of a text.
|
|
105
|
-
*/
|
|
106
|
-
export declare function wordSearch(query: string): (text: string) => boolean;
|
|
107
|
-
export { countOf };
|
|
81
|
+
export { countOf, searchKey, wordSearch };
|
|
108
82
|
//# sourceMappingURL=index.d.ts.map
|
package/build/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/error.ts","../src/escape.ts"
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/error.ts","../src/escape.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;wBAkBgB,aAAa;;;;;;;;wBCHb,WAAW;;;;;;;;wBAWX,gBAAgB;;;;;;;;;wBAYhB,aAAa;;;;;;;;;;;;wBAeb,eAAe;;;;;;;;wBAWf,mBAAmB;;;;;;;;wBAWnB,uBAAuB"}
|
package/build/index.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { countOf } from "./english.js";
|
|
2
2
|
import { a as escapeWorkflowData, i as escapeRegExp, n as escapeHtml, o as escapeWorkflowProperty, r as escapeMarkdown, t as escapeAttribute } from "./escape-vfOeIxac.js";
|
|
3
|
+
import { searchKey, wordSearch } from "./search.js";
|
|
3
4
|
// src/error.ts
|
|
4
5
|
/**
|
|
5
6
|
* This module has the text of a thrown value.
|
|
@@ -34,46 +35,6 @@ function errorMessage(error) {
|
|
|
34
35
|
}
|
|
35
36
|
}
|
|
36
37
|
}
|
|
37
|
-
// src/search.ts
|
|
38
|
-
/**
|
|
39
|
-
* This module has a word search of plain text. A text agrees with a search when the text has each word of the search,
|
|
40
|
-
* in any order. The case of the letters is not significant.
|
|
41
|
-
*/
|
|
42
|
-
/** The small final sigma. Unicode case folding changes it to the small sigma, so a word agrees in each position. */
|
|
43
|
-
const FINAL_SIGMA = /ς/gu;
|
|
44
|
-
/**
|
|
45
|
-
* This function gives the search key of a text. `wordSearch` compares the keys of texts. The function does these steps:
|
|
46
|
-
*
|
|
47
|
-
* 1. It applies the Unicode normalization NFKC. Thus the ligature "fi" agrees with "fi", and full-width letters agree
|
|
48
|
-
* with ASCII letters.
|
|
49
|
-
* 2. It applies the full lower case, then the full upper case, then the full lower case. Thus "ß", "ẞ" and "SS" give
|
|
50
|
-
* "ss".
|
|
51
|
-
* 3. It changes the small final sigma "ς" to "σ", as Unicode case folding does.
|
|
52
|
-
* 4. It applies NFKC again.
|
|
53
|
-
*
|
|
54
|
-
* The steps use no rules of a locale. Thus the Turkish "İ" gives "i" with a combining dot above (U+0307), and the
|
|
55
|
-
* Turkish "ı" gives "i". The key of a key is the same key. Accents stay, so "é" does not agree with "e".
|
|
56
|
-
*
|
|
57
|
-
* @param text - The plain text.
|
|
58
|
-
* @returns The search key of the text.
|
|
59
|
-
*/
|
|
60
|
-
function searchKey(text) {
|
|
61
|
-
return text.normalize("NFKC").toLowerCase().toUpperCase().toLowerCase().replace(FINAL_SIGMA, "σ").normalize("NFKC");
|
|
62
|
-
}
|
|
63
|
-
/**
|
|
64
|
-
* This function gives the test of a search. The function makes the key of the search with `searchKey`. Then it splits
|
|
65
|
-
* the key into words at each run of white space, the class `\s` of a regular expression.
|
|
66
|
-
*
|
|
67
|
-
* The test tells if the key of a text contains each word, in any order. A word can be a part of a longer word, so the
|
|
68
|
-
* search "art" finds "Party". A search with no words agrees with each text.
|
|
69
|
-
*
|
|
70
|
-
* @param query - The search, as a person types it.
|
|
71
|
-
* @returns The test of a text.
|
|
72
|
-
*/
|
|
73
|
-
function wordSearch(query) {
|
|
74
|
-
const words = searchKey(query).split(/\s+/u).filter((word) => word !== "");
|
|
75
|
-
return (text) => words.length === 0 || words.every((word) => searchKey(text).includes(word));
|
|
76
|
-
}
|
|
77
38
|
export { countOf, errorMessage, escapeAttribute, escapeHtml, escapeMarkdown, escapeRegExp, escapeWorkflowData, escapeWorkflowProperty, searchKey, wordSearch };
|
|
78
39
|
|
|
79
40
|
//# sourceMappingURL=index.js.map
|
package/build/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../src/error.ts"
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/error.ts"],"sourcesContent":["/**\n * This module has the text of a thrown value.\n */\n\n/**\n * This function gives the text of a thrown value, for a log line or a message on a screen. It does not throw.\n *\n * - An object with a `message` text gives that text. The check reads the field, not `instanceof Error`, so an error\n * from another realm (a `vm` context or an `iframe`) also gives its message.\n * - An `Error` with a `message` that is not a text gives `String(message)`. The brand check of\n * `Object.prototype.toString` finds an `Error` of each realm.\n * - Each other value gives `String(value)`.\n * - When `String` throws, the function gives the tag of `Object.prototype.toString`, for example `[object Object]`.\n * - A revoked `Proxy` gives its `typeof` in brackets: `[object]`.\n *\n * @param error - The thrown value. It can be any value.\n * @returns The text of the value.\n */\nexport function errorMessage(error: unknown): string {\n try {\n if (typeof error === \"object\" && error !== null && \"message\" in error) {\n const message: unknown = error.message;\n if (typeof message === \"string\") return message;\n if (Object.prototype.toString.call(error) === \"[object Error]\") return String(message);\n }\n return String(error);\n } catch {\n // String() throws for an object with no prototype, for a toString that throws and for a message getter that throws.\n try {\n return Object.prototype.toString.call(error);\n } catch {\n // A revoked Proxy throws also here. The operator typeof never throws.\n return `[${typeof error}]`;\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAkBA,SAAgB,aAAa,OAAwB;CACnD,IAAI;EACF,IAAI,OAAO,UAAU,YAAY,UAAU,QAAQ,aAAa,OAAO;GACrE,MAAM,UAAmB,MAAM;GAC/B,IAAI,OAAO,YAAY,UAAU,OAAO;GACxC,IAAI,OAAO,UAAU,SAAS,KAAK,KAAK,MAAM,kBAAkB,OAAO,OAAO,OAAO;EACvF;EACA,OAAO,OAAO,KAAK;CACrB,QAAQ;EAEN,IAAI;GACF,OAAO,OAAO,UAAU,SAAS,KAAK,KAAK;EAC7C,QAAQ;GAEN,OAAO,IAAI,OAAO,MAAM;EAC1B;CACF;AACF"}
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* This function gives the search key of a text. `wordSearch` compares the keys of texts. The function does these steps:
|
|
3
|
+
*
|
|
4
|
+
* 1. It applies the Unicode normalization NFKC. Thus the ligature "fi" agrees with "fi", and full-width letters agree
|
|
5
|
+
* with ASCII letters.
|
|
6
|
+
* 2. It applies the full lower case, then the full upper case, then the full lower case. Thus "ß", "ẞ" and "SS" give
|
|
7
|
+
* "ss".
|
|
8
|
+
* 3. It changes the small final sigma "ς" to "σ", as Unicode case folding does.
|
|
9
|
+
* 4. It applies NFKC again.
|
|
10
|
+
*
|
|
11
|
+
* The steps use no rules of a locale. Thus the Turkish "İ" gives "i" with a combining dot above (U+0307), and the
|
|
12
|
+
* Turkish "ı" gives "i". The key of a key is the same key. Accents stay, so "é" does not agree with "e".
|
|
13
|
+
*
|
|
14
|
+
* @param text - The plain text.
|
|
15
|
+
* @returns The search key of the text.
|
|
16
|
+
*/
|
|
17
|
+
export declare function searchKey(text: string): string;
|
|
18
|
+
/**
|
|
19
|
+
* This function gives the test of a search. The function makes the key of the search with `searchKey`. Then it splits
|
|
20
|
+
* the key into words at each run of white space, the class `\s` of a regular expression.
|
|
21
|
+
*
|
|
22
|
+
* The test tells if the key of a text contains each word, in any order. A word can be a part of a longer word, so the
|
|
23
|
+
* search "art" finds "Party". A search with no words agrees with each text.
|
|
24
|
+
*
|
|
25
|
+
* @param query - The search, as a person types it.
|
|
26
|
+
* @returns The test of a text.
|
|
27
|
+
*/
|
|
28
|
+
export declare function wordSearch(query: string): (text: string) => boolean;
|
|
29
|
+
/** The options of `searchWords`. Each option is a rule of the caller, for example a list of stop words of a language. */
|
|
30
|
+
export interface WordOptions {
|
|
31
|
+
/** The words that do not go in, as search keys. */
|
|
32
|
+
readonly stop?: ReadonlySet<string>;
|
|
33
|
+
/** The test of a word after the stop words. A word goes in only when the test gives true. */
|
|
34
|
+
readonly keep?: (word: string) => boolean;
|
|
35
|
+
/** The change of a word that goes in, for example a cut of a plural ending. */
|
|
36
|
+
readonly stem?: (word: string) => string;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* This function gives the words of a text, in their order, for a ranked search. The function does these steps:
|
|
40
|
+
*
|
|
41
|
+
* 1. It makes the search key of the text with `searchKey`.
|
|
42
|
+
* 2. It divides the key into word segments with `Intl.Segmenter` (Unicode Standard Annex 29). It keeps only the segments
|
|
43
|
+
* that are words or numbers, not spaces or punctuation.
|
|
44
|
+
* 3. It removes each word of `options.stop`, then each word that `options.keep` refuses.
|
|
45
|
+
* 4. It applies `options.stem` to each word that stays.
|
|
46
|
+
*
|
|
47
|
+
* @param text - The plain text.
|
|
48
|
+
* @param options - The rules of the caller. With no options, each word goes in with no change.
|
|
49
|
+
* @returns The words of the text.
|
|
50
|
+
*/
|
|
51
|
+
export declare function searchWords(text: string, options?: WordOptions): string[];
|
|
52
|
+
/**
|
|
53
|
+
* The two forms of the inverse document frequency (IDF) of a term. N is the count of documents, and df is the count of
|
|
54
|
+
* the documents that have the term.
|
|
55
|
+
*
|
|
56
|
+
* - `plain` is ln(N / df). A term in each document has the weight 0, so it does not change a rank.
|
|
57
|
+
* - `smooth` is ln((N + 1) / (df + 1)) + 1, as scikit-learn computes it. Each term has a weight of 1 or more.
|
|
58
|
+
*/
|
|
59
|
+
export type IdfForm = "plain" | "smooth";
|
|
60
|
+
/**
|
|
61
|
+
* This function gives the inverse document frequency of each term of a corpus. A document is a list of words, for
|
|
62
|
+
* example from `searchWords`. A term counts one time in each document that has it.
|
|
63
|
+
*
|
|
64
|
+
* The weight of a term depends only on N and on its df. Thus the order of the documents does not change a weight.
|
|
65
|
+
*
|
|
66
|
+
* @param documents - The corpus.
|
|
67
|
+
* @param form - The form of the IDF. The default is `plain`.
|
|
68
|
+
* @returns The IDF of each term of the corpus.
|
|
69
|
+
*/
|
|
70
|
+
export declare function inverseDocumentFrequency(documents: readonly (readonly string[])[], form?: IdfForm): Map<string, number>;
|
|
71
|
+
/**
|
|
72
|
+
* This function gives the TF-IDF vector of a list of words, with a length of 1.
|
|
73
|
+
*
|
|
74
|
+
* - The weight of a term is (1 + ln(tf)) × idf, where tf is the count of the term in the list.
|
|
75
|
+
* - A term with a weight of 0, or with no IDF, is not in the vector.
|
|
76
|
+
* - A list with no term of weight above 0 gives an empty vector.
|
|
77
|
+
*
|
|
78
|
+
* @param words - The words of a document or of a query.
|
|
79
|
+
* @param idf - The IDF of each term, from `inverseDocumentFrequency`.
|
|
80
|
+
* @returns The weight of each term, divided by the Euclidean length of the vector.
|
|
81
|
+
*/
|
|
82
|
+
export declare function termVector(words: readonly string[], idf: ReadonlyMap<string, number>): Map<string, number>;
|
|
83
|
+
/**
|
|
84
|
+
* This function gives the cosine similarity of two vectors with a length of 1, from `termVector`. The similarity is the
|
|
85
|
+
* sum of the products of the weights of each term in the two vectors. It is 0 when the vectors have no term in common.
|
|
86
|
+
* The function clamps the sum to 0 to 1. Thus a vector with itself gives exactly 1, and not 1 plus a rounding error.
|
|
87
|
+
*
|
|
88
|
+
* @param a - The first vector.
|
|
89
|
+
* @param b - The second vector.
|
|
90
|
+
* @returns The similarity, from 0 to 1.
|
|
91
|
+
*/
|
|
92
|
+
export declare function cosineSimilarity(a: ReadonlyMap<string, number>, b: ReadonlyMap<string, number>): number;
|
|
93
|
+
/** The score of one document of a corpus for a query. */
|
|
94
|
+
export interface DocumentScore {
|
|
95
|
+
/** The position of the document in the corpus. */
|
|
96
|
+
readonly index: number;
|
|
97
|
+
/** The cosine similarity of the TF-IDF vectors of the document and of the query. */
|
|
98
|
+
readonly score: number;
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* This function ranks the documents of a corpus for a query with TF-IDF and the cosine similarity. It has no I/O.
|
|
102
|
+
*
|
|
103
|
+
* - The IDF comes from the corpus only. A term of the query that is not in the corpus has no weight.
|
|
104
|
+
* - The result has one score for each document, from the best to the worst. A tie keeps the order of the corpus.
|
|
105
|
+
* - The score of a document does not change when the order of the other documents changes.
|
|
106
|
+
*
|
|
107
|
+
* @param corpus - The documents, each as a list of words.
|
|
108
|
+
* @param query - The words of the query.
|
|
109
|
+
* @param form - The form of the IDF. The default is `plain`.
|
|
110
|
+
* @returns The score of each document, best first.
|
|
111
|
+
*/
|
|
112
|
+
export declare function rankDocuments(corpus: readonly (readonly string[])[], query: readonly string[], form?: IdfForm): DocumentScore[];
|
|
113
|
+
//# sourceMappingURL=search.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"search.d.ts","names":[],"sources":["../src/search.ts"],"mappings":";;;;;;;;;;;;;;;;wBA2BgB,UAAU;;;;;;;;;;;wBAcV,WAAW,iBAAiB;;iBAQ3B;;WAEN,OAAO;;WAEP,QAAQ;;WAER,QAAQ;;;;;;;;;;;;;;;wBAmBH,YAAY,cAAc,UAAS;;;;;;;;YAmBvC;;;;;;;;;;;wBAYI,yBAAyB,2CAA2C,OAAM,UAAoB;;;;;;;;;;;;wBAkB9F,WAAW,0BAA0B,KAAK,8BAA8B;;;;;;;;;;wBA0BxE,iBAAiB,GAAG,6BAA6B,GAAG;;iBAQnD;;WAEN;;WAEA;;;;;;;;;;;;;;wBAeK,cAAc,wCAAwC,0BAA0B,OAAM,UAAoB"}
|
package/build/search.js
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
// src/search.ts
|
|
2
|
+
/**
|
|
3
|
+
* This module has a word search of plain text. A text agrees with a search when the text has each word of the search,
|
|
4
|
+
* in any order. The case of the letters is not significant.
|
|
5
|
+
*
|
|
6
|
+
* The module also has a ranked search: the words of a text (`searchWords`), TF-IDF weights and the cosine similarity.
|
|
7
|
+
* `rankDocuments` puts the documents of a corpus in order for a query. Each function has no I/O.
|
|
8
|
+
*/
|
|
9
|
+
/** The small final sigma. Unicode case folding changes it to the small sigma, so a word agrees in each position. */
|
|
10
|
+
const FINAL_SIGMA = /ς/gu;
|
|
11
|
+
/**
|
|
12
|
+
* This function gives the search key of a text. `wordSearch` compares the keys of texts. The function does these steps:
|
|
13
|
+
*
|
|
14
|
+
* 1. It applies the Unicode normalization NFKC. Thus the ligature "fi" agrees with "fi", and full-width letters agree
|
|
15
|
+
* with ASCII letters.
|
|
16
|
+
* 2. It applies the full lower case, then the full upper case, then the full lower case. Thus "ß", "ẞ" and "SS" give
|
|
17
|
+
* "ss".
|
|
18
|
+
* 3. It changes the small final sigma "ς" to "σ", as Unicode case folding does.
|
|
19
|
+
* 4. It applies NFKC again.
|
|
20
|
+
*
|
|
21
|
+
* The steps use no rules of a locale. Thus the Turkish "İ" gives "i" with a combining dot above (U+0307), and the
|
|
22
|
+
* Turkish "ı" gives "i". The key of a key is the same key. Accents stay, so "é" does not agree with "e".
|
|
23
|
+
*
|
|
24
|
+
* @param text - The plain text.
|
|
25
|
+
* @returns The search key of the text.
|
|
26
|
+
*/
|
|
27
|
+
function searchKey(text) {
|
|
28
|
+
return text.normalize("NFKC").toLowerCase().toUpperCase().toLowerCase().replace(FINAL_SIGMA, "σ").normalize("NFKC");
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* This function gives the test of a search. The function makes the key of the search with `searchKey`. Then it splits
|
|
32
|
+
* the key into words at each run of white space, the class `\s` of a regular expression.
|
|
33
|
+
*
|
|
34
|
+
* The test tells if the key of a text contains each word, in any order. A word can be a part of a longer word, so the
|
|
35
|
+
* search "art" finds "Party". A search with no words agrees with each text.
|
|
36
|
+
*
|
|
37
|
+
* @param query - The search, as a person types it.
|
|
38
|
+
* @returns The test of a text.
|
|
39
|
+
*/
|
|
40
|
+
function wordSearch(query) {
|
|
41
|
+
const words = searchKey(query).split(/\s+/u).filter((word) => word !== "");
|
|
42
|
+
return (text) => words.length === 0 || words.every((word) => searchKey(text).includes(word));
|
|
43
|
+
}
|
|
44
|
+
/** The word segmenter of `searchWords`. A segmenter is costly to make, so the module makes it one time, at the first use. */
|
|
45
|
+
let wordSegmenter;
|
|
46
|
+
/**
|
|
47
|
+
* This function gives the words of a text, in their order, for a ranked search. The function does these steps:
|
|
48
|
+
*
|
|
49
|
+
* 1. It makes the search key of the text with `searchKey`.
|
|
50
|
+
* 2. It divides the key into word segments with `Intl.Segmenter` (Unicode Standard Annex 29). It keeps only the segments
|
|
51
|
+
* that are words or numbers, not spaces or punctuation.
|
|
52
|
+
* 3. It removes each word of `options.stop`, then each word that `options.keep` refuses.
|
|
53
|
+
* 4. It applies `options.stem` to each word that stays.
|
|
54
|
+
*
|
|
55
|
+
* @param text - The plain text.
|
|
56
|
+
* @param options - The rules of the caller. With no options, each word goes in with no change.
|
|
57
|
+
* @returns The words of the text.
|
|
58
|
+
*/
|
|
59
|
+
function searchWords(text, options = {}) {
|
|
60
|
+
const out = [];
|
|
61
|
+
wordSegmenter ??= new Intl.Segmenter("en", { granularity: "word" });
|
|
62
|
+
for (const segment of wordSegmenter.segment(searchKey(text))) {
|
|
63
|
+
if (!segment.isWordLike) continue;
|
|
64
|
+
const word = segment.segment;
|
|
65
|
+
if (options.stop?.has(word) || options.keep && !options.keep(word)) continue;
|
|
66
|
+
out.push(options.stem ? options.stem(word) : word);
|
|
67
|
+
}
|
|
68
|
+
return out;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* This function gives the inverse document frequency of each term of a corpus. A document is a list of words, for
|
|
72
|
+
* example from `searchWords`. A term counts one time in each document that has it.
|
|
73
|
+
*
|
|
74
|
+
* The weight of a term depends only on N and on its df. Thus the order of the documents does not change a weight.
|
|
75
|
+
*
|
|
76
|
+
* @param documents - The corpus.
|
|
77
|
+
* @param form - The form of the IDF. The default is `plain`.
|
|
78
|
+
* @returns The IDF of each term of the corpus.
|
|
79
|
+
*/
|
|
80
|
+
function inverseDocumentFrequency(documents, form = "plain") {
|
|
81
|
+
const df = /* @__PURE__ */ new Map();
|
|
82
|
+
for (const document of documents) for (const term of new Set(document)) df.set(term, (df.get(term) ?? 0) + 1);
|
|
83
|
+
const n = documents.length;
|
|
84
|
+
return new Map([...df].map(([term, count]) => [term, form === "plain" ? Math.log(n / count) : Math.log((n + 1) / (count + 1)) + 1]));
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* This function gives the TF-IDF vector of a list of words, with a length of 1.
|
|
88
|
+
*
|
|
89
|
+
* - The weight of a term is (1 + ln(tf)) × idf, where tf is the count of the term in the list.
|
|
90
|
+
* - A term with a weight of 0, or with no IDF, is not in the vector.
|
|
91
|
+
* - A list with no term of weight above 0 gives an empty vector.
|
|
92
|
+
*
|
|
93
|
+
* @param words - The words of a document or of a query.
|
|
94
|
+
* @param idf - The IDF of each term, from `inverseDocumentFrequency`.
|
|
95
|
+
* @returns The weight of each term, divided by the Euclidean length of the vector.
|
|
96
|
+
*/
|
|
97
|
+
function termVector(words, idf) {
|
|
98
|
+
const tf = /* @__PURE__ */ new Map();
|
|
99
|
+
for (const word of words) tf.set(word, (tf.get(word) ?? 0) + 1);
|
|
100
|
+
const vector = /* @__PURE__ */ new Map();
|
|
101
|
+
let norm = 0;
|
|
102
|
+
for (const [term, count] of tf) {
|
|
103
|
+
const weight = (1 + Math.log(count)) * (idf.get(term) ?? 0);
|
|
104
|
+
if (weight > 0) {
|
|
105
|
+
vector.set(term, weight);
|
|
106
|
+
norm += weight * weight;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
norm = Math.sqrt(norm);
|
|
110
|
+
if (norm > 0) for (const [term, weight] of vector) vector.set(term, weight / norm);
|
|
111
|
+
return vector;
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* This function gives the cosine similarity of two vectors with a length of 1, from `termVector`. The similarity is the
|
|
115
|
+
* sum of the products of the weights of each term in the two vectors. It is 0 when the vectors have no term in common.
|
|
116
|
+
* The function clamps the sum to 0 to 1. Thus a vector with itself gives exactly 1, and not 1 plus a rounding error.
|
|
117
|
+
*
|
|
118
|
+
* @param a - The first vector.
|
|
119
|
+
* @param b - The second vector.
|
|
120
|
+
* @returns The similarity, from 0 to 1.
|
|
121
|
+
*/
|
|
122
|
+
function cosineSimilarity(a, b) {
|
|
123
|
+
const [small, large] = a.size < b.size ? [a, b] : [b, a];
|
|
124
|
+
let sum = 0;
|
|
125
|
+
for (const [term, weight] of small) sum += weight * (large.get(term) ?? 0);
|
|
126
|
+
return Math.min(1, Math.max(0, sum));
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* This function ranks the documents of a corpus for a query with TF-IDF and the cosine similarity. It has no I/O.
|
|
130
|
+
*
|
|
131
|
+
* - The IDF comes from the corpus only. A term of the query that is not in the corpus has no weight.
|
|
132
|
+
* - The result has one score for each document, from the best to the worst. A tie keeps the order of the corpus.
|
|
133
|
+
* - The score of a document does not change when the order of the other documents changes.
|
|
134
|
+
*
|
|
135
|
+
* @param corpus - The documents, each as a list of words.
|
|
136
|
+
* @param query - The words of the query.
|
|
137
|
+
* @param form - The form of the IDF. The default is `plain`.
|
|
138
|
+
* @returns The score of each document, best first.
|
|
139
|
+
*/
|
|
140
|
+
function rankDocuments(corpus, query, form = "plain") {
|
|
141
|
+
const idf = inverseDocumentFrequency(corpus, form);
|
|
142
|
+
const q = termVector(query, idf);
|
|
143
|
+
return corpus.map((document, index) => ({
|
|
144
|
+
index,
|
|
145
|
+
score: cosineSimilarity(q, termVector(document, idf))
|
|
146
|
+
})).sort((a, b) => b.score - a.score);
|
|
147
|
+
}
|
|
148
|
+
export { cosineSimilarity, inverseDocumentFrequency, rankDocuments, searchKey, searchWords, termVector, wordSearch };
|
|
149
|
+
|
|
150
|
+
//# sourceMappingURL=search.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"search.js","names":[],"sources":["../src/search.ts"],"sourcesContent":["/**\n * This module has a word search of plain text. A text agrees with a search when the text has each word of the search,\n * in any order. The case of the letters is not significant.\n *\n * The module also has a ranked search: the words of a text (`searchWords`), TF-IDF weights and the cosine similarity.\n * `rankDocuments` puts the documents of a corpus in order for a query. Each function has no I/O.\n */\n\n/** The small final sigma. Unicode case folding changes it to the small sigma, so a word agrees in each position. */\nconst FINAL_SIGMA = /ς/gu;\n\n/**\n * This function gives the search key of a text. `wordSearch` compares the keys of texts. The function does these steps:\n *\n * 1. It applies the Unicode normalization NFKC. Thus the ligature \"fi\" agrees with \"fi\", and full-width letters agree\n * with ASCII letters.\n * 2. It applies the full lower case, then the full upper case, then the full lower case. Thus \"ß\", \"ẞ\" and \"SS\" give\n * \"ss\".\n * 3. It changes the small final sigma \"ς\" to \"σ\", as Unicode case folding does.\n * 4. It applies NFKC again.\n *\n * The steps use no rules of a locale. Thus the Turkish \"İ\" gives \"i\" with a combining dot above (U+0307), and the\n * Turkish \"ı\" gives \"i\". The key of a key is the same key. Accents stay, so \"é\" does not agree with \"e\".\n *\n * @param text - The plain text.\n * @returns The search key of the text.\n */\nexport function searchKey(text: string): string {\n return text.normalize(\"NFKC\").toLowerCase().toUpperCase().toLowerCase().replace(FINAL_SIGMA, \"σ\").normalize(\"NFKC\");\n}\n\n/**\n * This function gives the test of a search. The function makes the key of the search with `searchKey`. Then it splits\n * the key into words at each run of white space, the class `\\s` of a regular expression.\n *\n * The test tells if the key of a text contains each word, in any order. A word can be a part of a longer word, so the\n * search \"art\" finds \"Party\". A search with no words agrees with each text.\n *\n * @param query - The search, as a person types it.\n * @returns The test of a text.\n */\nexport function wordSearch(query: string): (text: string) => boolean {\n const words = searchKey(query)\n .split(/\\s+/u)\n .filter((word) => word !== \"\");\n return (text) => words.length === 0 || words.every((word) => searchKey(text).includes(word));\n}\n\n/** The options of `searchWords`. Each option is a rule of the caller, for example a list of stop words of a language. */\nexport interface WordOptions {\n /** The words that do not go in, as search keys. */\n readonly stop?: ReadonlySet<string>;\n /** The test of a word after the stop words. A word goes in only when the test gives true. */\n readonly keep?: (word: string) => boolean;\n /** The change of a word that goes in, for example a cut of a plural ending. */\n readonly stem?: (word: string) => string;\n}\n\n/** The word segmenter of `searchWords`. A segmenter is costly to make, so the module makes it one time, at the first use. */\nlet wordSegmenter: Intl.Segmenter | undefined;\n\n/**\n * This function gives the words of a text, in their order, for a ranked search. The function does these steps:\n *\n * 1. It makes the search key of the text with `searchKey`.\n * 2. It divides the key into word segments with `Intl.Segmenter` (Unicode Standard Annex 29). It keeps only the segments\n * that are words or numbers, not spaces or punctuation.\n * 3. It removes each word of `options.stop`, then each word that `options.keep` refuses.\n * 4. It applies `options.stem` to each word that stays.\n *\n * @param text - The plain text.\n * @param options - The rules of the caller. With no options, each word goes in with no change.\n * @returns The words of the text.\n */\nexport function searchWords(text: string, options: WordOptions = {}): string[] {\n const out: string[] = [];\n wordSegmenter ??= new Intl.Segmenter(\"en\", { granularity: \"word\" });\n for (const segment of wordSegmenter.segment(searchKey(text))) {\n if (!segment.isWordLike) continue;\n const word = segment.segment;\n if (options.stop?.has(word) || (options.keep && !options.keep(word))) continue;\n out.push(options.stem ? options.stem(word) : word);\n }\n return out;\n}\n\n/**\n * The two forms of the inverse document frequency (IDF) of a term. N is the count of documents, and df is the count of\n * the documents that have the term.\n *\n * - `plain` is ln(N / df). A term in each document has the weight 0, so it does not change a rank.\n * - `smooth` is ln((N + 1) / (df + 1)) + 1, as scikit-learn computes it. Each term has a weight of 1 or more.\n */\nexport type IdfForm = \"plain\" | \"smooth\";\n\n/**\n * This function gives the inverse document frequency of each term of a corpus. A document is a list of words, for\n * example from `searchWords`. A term counts one time in each document that has it.\n *\n * The weight of a term depends only on N and on its df. Thus the order of the documents does not change a weight.\n *\n * @param documents - The corpus.\n * @param form - The form of the IDF. The default is `plain`.\n * @returns The IDF of each term of the corpus.\n */\nexport function inverseDocumentFrequency(documents: readonly (readonly string[])[], form: IdfForm = \"plain\"): Map<string, number> {\n const df = new Map<string, number>();\n for (const document of documents) for (const term of new Set(document)) df.set(term, (df.get(term) ?? 0) + 1);\n const n = documents.length;\n return new Map([...df].map(([term, count]) => [term, form === \"plain\" ? Math.log(n / count) : Math.log((n + 1) / (count + 1)) + 1]));\n}\n\n/**\n * This function gives the TF-IDF vector of a list of words, with a length of 1.\n *\n * - The weight of a term is (1 + ln(tf)) × idf, where tf is the count of the term in the list.\n * - A term with a weight of 0, or with no IDF, is not in the vector.\n * - A list with no term of weight above 0 gives an empty vector.\n *\n * @param words - The words of a document or of a query.\n * @param idf - The IDF of each term, from `inverseDocumentFrequency`.\n * @returns The weight of each term, divided by the Euclidean length of the vector.\n */\nexport function termVector(words: readonly string[], idf: ReadonlyMap<string, number>): Map<string, number> {\n const tf = new Map<string, number>();\n for (const word of words) tf.set(word, (tf.get(word) ?? 0) + 1);\n const vector = new Map<string, number>();\n let norm = 0;\n for (const [term, count] of tf) {\n const weight = (1 + Math.log(count)) * (idf.get(term) ?? 0);\n if (weight > 0) {\n vector.set(term, weight);\n norm += weight * weight;\n }\n }\n norm = Math.sqrt(norm);\n if (norm > 0) for (const [term, weight] of vector) vector.set(term, weight / norm);\n return vector;\n}\n\n/**\n * This function gives the cosine similarity of two vectors with a length of 1, from `termVector`. The similarity is the\n * sum of the products of the weights of each term in the two vectors. It is 0 when the vectors have no term in common.\n * The function clamps the sum to 0 to 1. Thus a vector with itself gives exactly 1, and not 1 plus a rounding error.\n *\n * @param a - The first vector.\n * @param b - The second vector.\n * @returns The similarity, from 0 to 1.\n */\nexport function cosineSimilarity(a: ReadonlyMap<string, number>, b: ReadonlyMap<string, number>): number {\n const [small, large] = a.size < b.size ? [a, b] : [b, a];\n let sum = 0;\n for (const [term, weight] of small) sum += weight * (large.get(term) ?? 0);\n return Math.min(1, Math.max(0, sum));\n}\n\n/** The score of one document of a corpus for a query. */\nexport interface DocumentScore {\n /** The position of the document in the corpus. */\n readonly index: number;\n /** The cosine similarity of the TF-IDF vectors of the document and of the query. */\n readonly score: number;\n}\n\n/**\n * This function ranks the documents of a corpus for a query with TF-IDF and the cosine similarity. It has no I/O.\n *\n * - The IDF comes from the corpus only. A term of the query that is not in the corpus has no weight.\n * - The result has one score for each document, from the best to the worst. A tie keeps the order of the corpus.\n * - The score of a document does not change when the order of the other documents changes.\n *\n * @param corpus - The documents, each as a list of words.\n * @param query - The words of the query.\n * @param form - The form of the IDF. The default is `plain`.\n * @returns The score of each document, best first.\n */\nexport function rankDocuments(corpus: readonly (readonly string[])[], query: readonly string[], form: IdfForm = \"plain\"): DocumentScore[] {\n const idf = inverseDocumentFrequency(corpus, form);\n const q = termVector(query, idf);\n return corpus.map((document, index) => ({ index, score: cosineSimilarity(q, termVector(document, idf)) })).sort((a, b) => b.score - a.score);\n}\n"],"mappings":"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"}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"$schema": "https://json.schemastore.org/package",
|
|
3
3
|
"name": "@mark1russell7/text",
|
|
4
|
-
"version": "0.0.
|
|
4
|
+
"version": "0.0.14",
|
|
5
5
|
"description": "Plain text helpers: the escapes for HTML, attributes, patterns, Markdown and workflow commands, English word forms (countOf, listOf), a word search (wordSearch), the text of a thrown value (errorMessage), the orders of texts by code units and by code points (compareCodeUnits, compareCodePoints), the removal of secrets (redactSecrets) and the shapes of tokens and of secrets by their context (findSecretShapes, redactSecretShapes, findSecretShapesInValue, CONTEXT_SHAPES, isSecretName), and lengths in code units, code points and graphemes with truncation and padding (textLength, truncate, pad), the marked parts of a text (partsAt, partsOf), and a scan of HTML for its text and its start tags (scanHtml).",
|
|
6
6
|
"keywords": [
|
|
7
7
|
"text",
|
|
@@ -64,6 +64,10 @@
|
|
|
64
64
|
"types": "./build/english.d.ts",
|
|
65
65
|
"default": "./build/english.js"
|
|
66
66
|
},
|
|
67
|
+
"./search": {
|
|
68
|
+
"types": "./build/search.d.ts",
|
|
69
|
+
"default": "./build/search.js"
|
|
70
|
+
},
|
|
67
71
|
"./package.json": "./package.json"
|
|
68
72
|
},
|
|
69
73
|
"files": [
|
|
@@ -79,7 +83,7 @@
|
|
|
79
83
|
},
|
|
80
84
|
"devDependencies": {
|
|
81
85
|
"@mark1russell7/cue": "^2.0.0",
|
|
82
|
-
"@mark1russell7/rigor-generators": "^0.
|
|
86
|
+
"@mark1russell7/rigor-generators": "^0.2.0",
|
|
83
87
|
"@types/node": "^26.6.5",
|
|
84
88
|
"@vitest/coverage-v8": "^5.0.3",
|
|
85
89
|
"esbuild": "^0.28.2",
|
package/src/index.ts
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
* expressions, Markdown and GitHub Actions workflow commands. The other groups are the English word forms, a word
|
|
4
4
|
* search and the text of a thrown value. The entry `@mark1russell7/text/redact` removes secrets from a text, and the entry
|
|
5
5
|
* `@mark1russell7/text/order` has two orders of texts. The entry `@mark1russell7/text/english` adds the list join `listOf`.
|
|
6
|
+
* The entry `@mark1russell7/text/search` adds a ranked search with TF-IDF.
|
|
6
7
|
*/
|
|
7
8
|
export { countOf } from "./english.ts";
|
|
8
9
|
export { errorMessage } from "./error.ts";
|
package/src/search.ts
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* This module has a word search of plain text. A text agrees with a search when the text has each word of the search,
|
|
3
3
|
* in any order. The case of the letters is not significant.
|
|
4
|
+
*
|
|
5
|
+
* The module also has a ranked search: the words of a text (`searchWords`), TF-IDF weights and the cosine similarity.
|
|
6
|
+
* `rankDocuments` puts the documents of a corpus in order for a query. Each function has no I/O.
|
|
4
7
|
*/
|
|
5
8
|
|
|
6
9
|
/** The small final sigma. Unicode case folding changes it to the small sigma, so a word agrees in each position. */
|
|
@@ -42,3 +45,137 @@ export function wordSearch(query: string): (text: string) => boolean {
|
|
|
42
45
|
.filter((word) => word !== "");
|
|
43
46
|
return (text) => words.length === 0 || words.every((word) => searchKey(text).includes(word));
|
|
44
47
|
}
|
|
48
|
+
|
|
49
|
+
/** The options of `searchWords`. Each option is a rule of the caller, for example a list of stop words of a language. */
|
|
50
|
+
export interface WordOptions {
|
|
51
|
+
/** The words that do not go in, as search keys. */
|
|
52
|
+
readonly stop?: ReadonlySet<string>;
|
|
53
|
+
/** The test of a word after the stop words. A word goes in only when the test gives true. */
|
|
54
|
+
readonly keep?: (word: string) => boolean;
|
|
55
|
+
/** The change of a word that goes in, for example a cut of a plural ending. */
|
|
56
|
+
readonly stem?: (word: string) => string;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** The word segmenter of `searchWords`. A segmenter is costly to make, so the module makes it one time, at the first use. */
|
|
60
|
+
let wordSegmenter: Intl.Segmenter | undefined;
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* This function gives the words of a text, in their order, for a ranked search. The function does these steps:
|
|
64
|
+
*
|
|
65
|
+
* 1. It makes the search key of the text with `searchKey`.
|
|
66
|
+
* 2. It divides the key into word segments with `Intl.Segmenter` (Unicode Standard Annex 29). It keeps only the segments
|
|
67
|
+
* that are words or numbers, not spaces or punctuation.
|
|
68
|
+
* 3. It removes each word of `options.stop`, then each word that `options.keep` refuses.
|
|
69
|
+
* 4. It applies `options.stem` to each word that stays.
|
|
70
|
+
*
|
|
71
|
+
* @param text - The plain text.
|
|
72
|
+
* @param options - The rules of the caller. With no options, each word goes in with no change.
|
|
73
|
+
* @returns The words of the text.
|
|
74
|
+
*/
|
|
75
|
+
export function searchWords(text: string, options: WordOptions = {}): string[] {
|
|
76
|
+
const out: string[] = [];
|
|
77
|
+
wordSegmenter ??= new Intl.Segmenter("en", { granularity: "word" });
|
|
78
|
+
for (const segment of wordSegmenter.segment(searchKey(text))) {
|
|
79
|
+
if (!segment.isWordLike) continue;
|
|
80
|
+
const word = segment.segment;
|
|
81
|
+
if (options.stop?.has(word) || (options.keep && !options.keep(word))) continue;
|
|
82
|
+
out.push(options.stem ? options.stem(word) : word);
|
|
83
|
+
}
|
|
84
|
+
return out;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* The two forms of the inverse document frequency (IDF) of a term. N is the count of documents, and df is the count of
|
|
89
|
+
* the documents that have the term.
|
|
90
|
+
*
|
|
91
|
+
* - `plain` is ln(N / df). A term in each document has the weight 0, so it does not change a rank.
|
|
92
|
+
* - `smooth` is ln((N + 1) / (df + 1)) + 1, as scikit-learn computes it. Each term has a weight of 1 or more.
|
|
93
|
+
*/
|
|
94
|
+
export type IdfForm = "plain" | "smooth";
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* This function gives the inverse document frequency of each term of a corpus. A document is a list of words, for
|
|
98
|
+
* example from `searchWords`. A term counts one time in each document that has it.
|
|
99
|
+
*
|
|
100
|
+
* The weight of a term depends only on N and on its df. Thus the order of the documents does not change a weight.
|
|
101
|
+
*
|
|
102
|
+
* @param documents - The corpus.
|
|
103
|
+
* @param form - The form of the IDF. The default is `plain`.
|
|
104
|
+
* @returns The IDF of each term of the corpus.
|
|
105
|
+
*/
|
|
106
|
+
export function inverseDocumentFrequency(documents: readonly (readonly string[])[], form: IdfForm = "plain"): Map<string, number> {
|
|
107
|
+
const df = new Map<string, number>();
|
|
108
|
+
for (const document of documents) for (const term of new Set(document)) df.set(term, (df.get(term) ?? 0) + 1);
|
|
109
|
+
const n = documents.length;
|
|
110
|
+
return new Map([...df].map(([term, count]) => [term, form === "plain" ? Math.log(n / count) : Math.log((n + 1) / (count + 1)) + 1]));
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* This function gives the TF-IDF vector of a list of words, with a length of 1.
|
|
115
|
+
*
|
|
116
|
+
* - The weight of a term is (1 + ln(tf)) × idf, where tf is the count of the term in the list.
|
|
117
|
+
* - A term with a weight of 0, or with no IDF, is not in the vector.
|
|
118
|
+
* - A list with no term of weight above 0 gives an empty vector.
|
|
119
|
+
*
|
|
120
|
+
* @param words - The words of a document or of a query.
|
|
121
|
+
* @param idf - The IDF of each term, from `inverseDocumentFrequency`.
|
|
122
|
+
* @returns The weight of each term, divided by the Euclidean length of the vector.
|
|
123
|
+
*/
|
|
124
|
+
export function termVector(words: readonly string[], idf: ReadonlyMap<string, number>): Map<string, number> {
|
|
125
|
+
const tf = new Map<string, number>();
|
|
126
|
+
for (const word of words) tf.set(word, (tf.get(word) ?? 0) + 1);
|
|
127
|
+
const vector = new Map<string, number>();
|
|
128
|
+
let norm = 0;
|
|
129
|
+
for (const [term, count] of tf) {
|
|
130
|
+
const weight = (1 + Math.log(count)) * (idf.get(term) ?? 0);
|
|
131
|
+
if (weight > 0) {
|
|
132
|
+
vector.set(term, weight);
|
|
133
|
+
norm += weight * weight;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
norm = Math.sqrt(norm);
|
|
137
|
+
if (norm > 0) for (const [term, weight] of vector) vector.set(term, weight / norm);
|
|
138
|
+
return vector;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* This function gives the cosine similarity of two vectors with a length of 1, from `termVector`. The similarity is the
|
|
143
|
+
* sum of the products of the weights of each term in the two vectors. It is 0 when the vectors have no term in common.
|
|
144
|
+
* The function clamps the sum to 0 to 1. Thus a vector with itself gives exactly 1, and not 1 plus a rounding error.
|
|
145
|
+
*
|
|
146
|
+
* @param a - The first vector.
|
|
147
|
+
* @param b - The second vector.
|
|
148
|
+
* @returns The similarity, from 0 to 1.
|
|
149
|
+
*/
|
|
150
|
+
export function cosineSimilarity(a: ReadonlyMap<string, number>, b: ReadonlyMap<string, number>): number {
|
|
151
|
+
const [small, large] = a.size < b.size ? [a, b] : [b, a];
|
|
152
|
+
let sum = 0;
|
|
153
|
+
for (const [term, weight] of small) sum += weight * (large.get(term) ?? 0);
|
|
154
|
+
return Math.min(1, Math.max(0, sum));
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** The score of one document of a corpus for a query. */
|
|
158
|
+
export interface DocumentScore {
|
|
159
|
+
/** The position of the document in the corpus. */
|
|
160
|
+
readonly index: number;
|
|
161
|
+
/** The cosine similarity of the TF-IDF vectors of the document and of the query. */
|
|
162
|
+
readonly score: number;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* This function ranks the documents of a corpus for a query with TF-IDF and the cosine similarity. It has no I/O.
|
|
167
|
+
*
|
|
168
|
+
* - The IDF comes from the corpus only. A term of the query that is not in the corpus has no weight.
|
|
169
|
+
* - The result has one score for each document, from the best to the worst. A tie keeps the order of the corpus.
|
|
170
|
+
* - The score of a document does not change when the order of the other documents changes.
|
|
171
|
+
*
|
|
172
|
+
* @param corpus - The documents, each as a list of words.
|
|
173
|
+
* @param query - The words of the query.
|
|
174
|
+
* @param form - The form of the IDF. The default is `plain`.
|
|
175
|
+
* @returns The score of each document, best first.
|
|
176
|
+
*/
|
|
177
|
+
export function rankDocuments(corpus: readonly (readonly string[])[], query: readonly string[], form: IdfForm = "plain"): DocumentScore[] {
|
|
178
|
+
const idf = inverseDocumentFrequency(corpus, form);
|
|
179
|
+
const q = termVector(query, idf);
|
|
180
|
+
return corpus.map((document, index) => ({ index, score: cosineSimilarity(q, termVector(document, idf)) })).sort((a, b) => b.score - a.score);
|
|
181
|
+
}
|