rust-fuzzy-search-0.1.1/.cargo_vcs_info.json0000644000000001120000000000000144510ustar { "git": { "sha1": "aa760d75df956f0c12a429be92e4350329e25246" } } rust-fuzzy-search-0.1.1/.gitignore000064400000000000000000000000500000000000000152100ustar 00000000000000target/* !target/doc/ Cargo.lock .idea/ rust-fuzzy-search-0.1.1/.gitlab-ci.yml000064400000000000000000000003520000000000000156610ustar 00000000000000stages: - deploy pages: image: rustdocker/rust:stable stage: deploy #only: # - master script: - cargo doc - rm -rf public - mkdir public - cp -R target/doc/* public artifacts: paths: - public rust-fuzzy-search-0.1.1/.idea/.gitignore000064400000000000000000000000570000000000000161770ustar 00000000000000# Default ignored files /shelf/ /workspace.xml rust-fuzzy-search-0.1.1/.idea/codeStyles/Project.xml000064400000000000000000000004070000000000000204540ustar 00000000000000 rust-fuzzy-search-0.1.1/.idea/codeStyles/codeStyleConfig.xml000064400000000000000000000002250000000000000221250ustar 00000000000000 rust-fuzzy-search-0.1.1/.idea/misc.xml000064400000000000000000000002540000000000000156630ustar 00000000000000 rust-fuzzy-search-0.1.1/.idea/modules.xml000064400000000000000000000004220000000000000163750ustar 00000000000000 rust-fuzzy-search-0.1.1/.idea/vcs.xml000064400000000000000000000002470000000000000155250ustar 00000000000000 rust-fuzzy-search-0.1.1/Cargo.lock0000644000000002410000000000000124270ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 3 [[package]] name = "rust-fuzzy-search" version = "0.1.1" rust-fuzzy-search-0.1.1/Cargo.toml0000644000000020350000000000000124550ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies # # If you believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're # editing this file be aware that the upstream Cargo.toml # will likely look very different (and much more reasonable) [package] edition = "2018" name = "rust-fuzzy-search" version = "0.1.1" authors = ["EnricoCh "] publish = true description = "Fuzzy Search with trigrams implemented in Rust" homepage = "https://gitlab.com/EnricoCh/rust-fuzzy-search" documentation = "https://enricoch.gitlab.io/rust-fuzzy-search/rust_fuzzy_search/index.html" keywords = ["fuzzy-search", "compare-strings", "fuzzy", "compare"] license = "MIT OR Apache-2.0" repository = "https://gitlab.com/EnricoCh/rust-fuzzy-search" [dependencies] rust-fuzzy-search-0.1.1/Cargo.toml.orig0000644000000011620000000000000134140ustar [package] name = "rust-fuzzy-search" version = "0.1.1" authors = ["EnricoCh "] edition = "2018" description = "Fuzzy Search with trigrams implemented in Rust" documentation = "https://enricoch.gitlab.io/rust-fuzzy-search/rust_fuzzy_search/index.html" repository = "https://gitlab.com/EnricoCh/rust-fuzzy-search" homepage = "https://gitlab.com/EnricoCh/rust-fuzzy-search" keywords = ["fuzzy-search", "compare-strings", "fuzzy", "compare"] publish = true license = "MIT OR Apache-2.0" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] rust-fuzzy-search-0.1.1/Cargo.toml.orig000064400000000000000000000011620000000000000161140ustar 00000000000000[package] name = "rust-fuzzy-search" version = "0.1.1" authors = ["EnricoCh "] edition = "2018" description = "Fuzzy Search with trigrams implemented in Rust" documentation = "https://enricoch.gitlab.io/rust-fuzzy-search/rust_fuzzy_search/index.html" repository = "https://gitlab.com/EnricoCh/rust-fuzzy-search" homepage = "https://gitlab.com/EnricoCh/rust-fuzzy-search" keywords = ["fuzzy-search", "compare-strings", "fuzzy", "compare"] publish = true license = "MIT OR Apache-2.0" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] rust-fuzzy-search-0.1.1/LICENSE-APACHE000064400000000000000000000261240000000000000151560ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2021 Enrico Chiaramello Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. rust-fuzzy-search-0.1.1/LICENSE-MIT000064400000000000000000000020630000000000000146620ustar 00000000000000MIT License Copyright (c) 2021 Enrico Chiaramello Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. rust-fuzzy-search-0.1.1/README.md000064400000000000000000000121200000000000000145000ustar 00000000000000# Rust Fuzzy Search | [Documentation](https://enricoch.gitlab.io/rust-fuzzy-search/rust_fuzzy_search/index.html) [](https://gitlab.com/EnricoCh/rust-fuzzy-search) [](https://enricoch.gitlab.io/rust-fuzzy-search/rust_fuzzy_search/index.html) [](https://gitlab.com/EnricoCh/rust-fuzzy-search/badges/master/pipeline.svg) [](https://www.rust-lang.org/) [](https://gitlab.com/EnricoCh/rust-fuzzy-search) ## Fuzzy search with trigrams implemented in Rust This crate implements Fuzzy Searching with trigrams Fuzzy searching allows to compare strings by similarity rather than by equality:\ Similar strings will get a high score (close to `1.0f32`) while dissimilar strings will get a lower score (closer to `0.0f32`). Fuzzy searching tolerates changes in word order:\ ex. `"John Dep"` and `"Dep John"` will get a high score. The Algorithm used is taken from : Basic idea: 1. From both strings extracts all groups of 3 adjacent letters.\ (`"House"` becomes `[' H', ' Ho', 'Hou', 'ous', 'use', 'se ']`).\ Note the 2 spaces added to the head of the string and the one on the tail, used to make the algorithm work on zero length words. 1. Then counts the number of trigrams of the first words that are also present on the second word and divide by the number of trigrams of the first word. Example: Comparing 2 strings ```rust fn test () { use rust_fuzzy_search::fuzzy_compare; let score : f32 = fuzzy_compare("kolbasobulko", "kolbasobulko"); println!("score = {:?}", score); } ``` Example: Comparing a string with a list of strings and retrieving only the best matches ```rust fn test() { use rust_fuzzy_search::fuzzy_search_best_n; let s = "bulko"; let list : Vec<&str> = vec![ "kolbasobulko", "sandviĉo", "ŝatas", "domo", "emuo", "fabo", "fazano" ]; let n : usize = 3; let res : Vec<(&str, f32)> = fuzzy_search_best_n(s,&list, n); for (_word, score) in res { println!("{:?}",score) } } ``` Example: if you have a `Vec` of `String`s you need to convert it to a list of `&str` ```rust fn works_with_strings() { use rust_fuzzy_search::fuzzy_search; let s = String::from("varma"); let list: Vec = vec![String::from("varma vetero"), String::from("varma ĉokolado")]; fuzzy_search(&s, &list.iter().map(String::as_ref).collect::>()); } ``` The crate exposes 5 main functions: - [fuzzy_compare](https://enricoch.gitlab.io/rust-fuzzy-search/rust_fuzzy_search/fn.fuzzy_compare.html) will take 2 strings and return a score representing how similar those strings are. - [fuzzy_search](https://enricoch.gitlab.io/rust-fuzzy-search/rust_fuzzy_search/fn.fuzzy_search.html) applies [fuzzy_compare](https://enricoch.gitlab.io/rust-fuzzy-search/rust_fuzzy_search/fn.fuzzy_compare.html) to a list of strings and returns a list of tuples: (word, score). - [fuzzy_search_sorted](https://enricoch.gitlab.io/rust-fuzzy-search/rust_fuzzy_search/fn.fuzzy_search_sorted.html) is similar to [fuzzy_search](https://enricoch.gitlab.io/rust-fuzzy-search/rust_fuzzy_search/fn.fuzzy_search.html) but orders the output in descending order. - [fuzzy_search_threshold](https://enricoch.gitlab.io/rust-fuzzy-search/rust_fuzzy_search/fn.fuzzy_search_threshold.html) will take an additional `f32` as input and returns only tuples with score greater than the threshold. - [fuzzy_search_best_n](https://enricoch.gitlab.io/rust-fuzzy-search/rust_fuzzy_search/fn.fuzzy_search_best_n.html) will take an additional `usize` arguments and returns the first `n` tuples. ## Usage To use this crate, first add this to your Cargo.toml: ```toml [dependencies] rust-fuzzy-search = { git = "https://gitlab.com/EnricoCh/rust-fuzzy-search"} ``` Next, add this to your crate: ```rust extern crate rust_fuzzy_search; use rust_fuzzy_search::*; fn main() { // ... } ``` ## Building To build the library use `cargo build` ## Testing To test the library use `cargo test` ## License Licensed under either of - Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://apache.org/licenses/LICENSE-2.0) - MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) ![MIT License](https://img.shields.io/static/v1.svg?label=📜%20License&message=MIT&color=informational) ![Apache 2.0 License](https://img.shields.io/static/v1.svg?label=📃%20License&message=Apache-2.0&color=informational) # Contribution Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.rust-fuzzy-search-0.1.1/public/.gitkeep000064400000000000000000000000000000000000000161220ustar 00000000000000rust-fuzzy-search-0.1.1/rust-fuzzy-search.iml000064400000000000000000000007400000000000000173560ustar 00000000000000 rust-fuzzy-search-0.1.1/src/lib.rs000064400000000000000000000252400000000000000151330ustar 00000000000000#![warn(missing_docs)] //#![doc(html_playground_url = "https://playground.example.com/")] // TODO add playground if possible //! This crate implements Fuzzy Searching with trigrams //! //! //! Fuzzy searching allows to compare strings by similarity rather than by equality:\ //! Similar strings will get a high score (close to `1.0f32`) while dissimilar strings will get a lower score (closer to `0.0f32`). //! //! Fuzzy searching tolerates changes in word order:\ //! ex. `"John Dep"` and `"Dep John"` will get a high score. //! //! //! The crate exposes 5 main functions: //! - [fuzzy_compare] will take 2 strings and return a score representing how similar those strings are. //! - [fuzzy_search] applies [fuzzy_compare] to a list of strings and returns a list of tuples: (word, score). //! - [fuzzy_search_sorted] is similar to [fuzzy_search] but orders the output in descending order. //! - [fuzzy_search_threshold] will take an additional `f32` as input and returns only tuples with score greater than the threshold. //! - [fuzzy_search_best_n] will take an additional `usize` arguments and returns the first `n` tuples. //! //! The Algorithm used is taken from : //! //! Basic idea: //! //! 1. From both strings extracts all groups of 3 adjacent letters.\ //! (`"House"` becomes `[' H', ' Ho', 'Hou', 'ous', 'use', 'se ']`).\ //! Note the 2 spaces added to the head of the string and the one on the tail, used to make the algorithm work on zero length words. //! //! 1. Then counts the number of trigrams of the first words that are also present on the second word and divide by the number of trigrams of the first word.\ //! //! //! Example: Comparing 2 strings //! ```rust //! fn test () { //! use rust_fuzzy_search::fuzzy_compare; //! let score : f32 = fuzzy_compare("kolbasobulko", "kolbasobulko"); //! println!("score = {:?}", score); //! } //! ``` //! //! Example: Comparing a string with a list of strings and retrieving only the best matches //! ```rust //! fn test() { //! use rust_fuzzy_search::fuzzy_search_best_n; //! let s = "bulko"; //! let list : Vec<&str> = vec![ //! "kolbasobulko", //! "sandviĉo", //! "ŝatas", //! "domo", //! "emuo", //! "fabo", //! "fazano" //! ]; //! let n : usize = 3; //! let res : Vec<(&str, f32)> = fuzzy_search_best_n(s,&list, n); //! for (_word, score) in res { //! println!("{:?}",score) //! } //! } //! ``` //! Example: if you have a `Vec` of `String`s you need to convert it to a list of `&str` //! ```rust //! fn works_with_strings() { //! use rust_fuzzy_search::fuzzy_search; //! let s = String::from("varma"); //! let list: Vec = vec![String::from("varma vetero"), String::from("varma ĉokolado")]; //! fuzzy_search(&s, &list.iter().map(String::as_ref).collect::>()); //! } //! ``` //! use std::iter; fn trigrams(s: &str) -> Vec<(char, char, char)> { let it_1 = iter::once(' ').chain(iter::once(' ')).chain(s.chars()); let it_2 = iter::once(' ').chain(s.chars()); let it_3 = s.chars().chain(iter::once(' ')); let res: Vec<(char, char, char)> = it_1 .zip(it_2) .zip(it_3) .map(|((a, b), c): ((char, char), char)| (a, b, c)) .collect(); res } /// Use this function to compare 2 strings. /// /// The output is a score (between `0.0f32 and 1.0f32`) representing how similar the 2 strings are. /// /// Arguments: /// * `a` : the first string to compare. /// * `b` : the second string to compare. /// /// /// example: /// ```rust /// fn test () { /// use rust_fuzzy_search::fuzzy_compare; /// let score : f32 = fuzzy_compare("kolbasobulko", "kolbasobulko"); /// println!("score = {:?}", score); /// } /// ``` pub fn fuzzy_compare(a: &str, b: &str) -> f32 { // gets length of first input string plus 1 (because of the 3 added spaces (' ')) let string_len = a.chars().count() + 1; // gets the trigrams for both strings let trigrams_a = trigrams(a); let trigrams_b = trigrams(b); // accumulator let mut acc: f32 = 0.0f32; // counts the number of trigrams of the first string that are also present in the second one for t_a in &trigrams_a { for t_b in &trigrams_b { if t_a == t_b { acc += 1.0f32; break; } } } let res = acc / (string_len as f32); // crops between zero and one if (0.0f32..=1.0f32).contains(&res) { res } else { 0.0f32 } } /// Use this function to compare a string (`&str`) with all elements of a list. /// /// /// The result is a list whose elements are tuples of the form `(string, score)`, the first element being the word of the list and the second element the score. /// /// Arguments: /// * `s` : the string to compare. /// * `list` : the list of strings to compare with `s`. /// /// example: /// ```rust /// fn test() { /// use rust_fuzzy_search::fuzzy_search; /// let s = "bulko"; /// let list : Vec<&str> = vec!["kolbasobulko", "sandviĉo"]; /// let res : Vec<(&str, f32)> = fuzzy_search(s,&list); /// for (_word, score) in res { /// println!("{:?}",score) /// } /// } /// ``` /// /// pub fn fuzzy_search<'a>(s: &'a str, list: &'a [&str]) -> Vec<(&'a str, f32)> { list.iter() .map(|&value| { let res = fuzzy_compare(s, value); (value, res) }) .collect() } /// This function is similar to [fuzzy_search] but sorts the result in descending order (the best matches are placed at the beginning). /// /// Arguments: /// * `s` : the string to compare. /// * `list` : the list of strings to compare with `s`. /// /// example: /// ```rust /// fn test() { /// use rust_fuzzy_search::fuzzy_search_sorted; /// let s = "bulko"; /// let list : Vec<&str> = vec!["kolbasobulko", "sandviĉo"]; /// let res : Vec<(&str, f32)> = fuzzy_search_sorted(s,&list); /// for (_word, score) in res { /// println!("{:?}",score) /// } /// } /// ``` /// pub fn fuzzy_search_sorted<'a>(s: &'a str, list: &'a [&str]) -> Vec<(&'a str, f32)> { let mut res = fuzzy_search(s, list); res.sort_by(|(_, d1), (_, d2)| d2.partial_cmp(d1).unwrap()); // TODO to fix the unwrap call res } /// This function is similar to [fuzzy_search] but filters out element with a score lower than the specified one. /// /// Arguments: /// * `s` : the string to compare. /// * `list` : the list of strings to compare with `s`. /// * `threshold` : the minimum allowed score for the elements in the result: elements with lower score will be removed. /// /// ```rust /// fn test() { /// use rust_fuzzy_search::fuzzy_search_threshold; /// let s = "bulko"; /// let list : Vec<&str> = vec!["kolbasobulko", "sandviĉo"]; /// let threshold : f32 = 0.4f32; /// let res : Vec<(&str, f32)> = fuzzy_search_threshold(s,&list, threshold); /// for (_word, score) in res { /// println!("{:?}",score) /// } /// } /// ``` pub fn fuzzy_search_threshold<'a>( s: &'a str, list: &'a [&str], threshold: f32, ) -> Vec<(&'a str, f32)> { fuzzy_search(s, list) .into_iter() .filter(|&(_, score)| score >= threshold) .collect() } /// This function is similar to [fuzzy_search_sorted] but keeps only the `n` best items, those with a better match. /// /// Arguments : /// * `s` : the string to compare. /// * `list` : the list of strings to compare with `s`. /// * `n` : the number of element to retrieve. /// /// example: /// ``` /// fn test() { /// use rust_fuzzy_search::fuzzy_search_best_n; /// let s = "bulko"; /// let list : Vec<&str> = vec!["kolbasobulko", "sandviĉo"]; /// let n : usize = 1; /// let res : Vec<(&str, f32)> = fuzzy_search_best_n(s,&list, n); /// for (_word, score) in res { /// println!("{:?}",score) /// } /// } /// ``` /// pub fn fuzzy_search_best_n<'a>(s: &'a str, list: &'a [&str], n: usize) -> Vec<(&'a str, f32)> { fuzzy_search_sorted(s, list).into_iter().take(n).collect() } #[cfg(test)] mod tests { use crate::{ fuzzy_compare, fuzzy_search, fuzzy_search_best_n, fuzzy_search_sorted, fuzzy_search_threshold, }; #[test] fn perfect_match_1() { assert_eq!(fuzzy_compare("kolbasobulko", "kolbasobulko"), 1.0f32) } #[test] fn perfect_match_2() { assert_eq!(fuzzy_compare("sandviĉo", "sandviĉo"), 1.0f32) } #[test] fn perfect_match_3() { assert_eq!(fuzzy_compare("domo", "domo"), 1.0f32) } #[test] fn perfect_match_4() { assert_eq!(fuzzy_compare("ŝatas", "ŝatas"), 1.0f32) } #[test] fn perfect_match_5() { assert_eq!(fuzzy_compare("mirinda estonto", "mirinda estonto"), 1.0f32) } #[test] fn no_match() { assert_eq!(fuzzy_compare("abc", "def"), 0.0f32) } #[test] fn empty_word() { assert_eq!(fuzzy_compare("", ""), 1.0f32) } #[test] fn one_letter() { assert_eq!(fuzzy_compare("a", "a"), 1.0f32) } #[test] fn utf8_one_letter_1() { assert_eq!(fuzzy_compare("ĉ", "ĉ"), 1.0f32) } #[test] fn utf8_one_letter_2() { assert_eq!(fuzzy_compare("ł", "ł"), 1.0f32) } #[test] fn utf8_no_match() { assert_eq!(fuzzy_compare("cgs", "ĉĝŝ"), 0.0f32) } #[test] fn test_fuzzy_search_1() { let s: &str = "bulko"; let list: Vec<&str> = vec!["kolbasobulko", "sandviĉo", "kolbasobulkejo"]; let res: Vec<(&str, f32)> = fuzzy_search(s, &list); assert_eq!(res.into_iter().count(), 3); } #[test] fn test_fuzzy_search_sorted() { let s: &str = "bulko"; let list: Vec<&str> = vec!["kolbasobulko", "sandviĉo", "kolbasobulkejo"]; let res: Vec<(&str, f32)> = fuzzy_search_sorted(s, &list); assert_eq!(res.into_iter().count(), 3); } #[test] fn no_lowers() { let threshold = 0.5f32; let s: &str = "bulko"; let list: Vec<&str> = vec!["kolbasobulko", "sandviĉo", "kolbasobulkejo"]; for (_word, score) in fuzzy_search_threshold(s, &list, threshold) { assert!(score > threshold) } } #[test] fn test_fuzzy_search_best_n() { let s: &str = "bulko"; let list: Vec<&str> = vec!["kolbasobulko", "sandviĉo", "kolbasobulkejo"]; let res: Vec<(&str, f32)> = fuzzy_search_best_n(s, &list, 2); assert_eq!(res.into_iter().count(), 2); } #[test] fn works_with_strings() { let s = String::from("varma"); let list: Vec = vec![String::from("varma vetero"), String::from("varma ĉokolado")]; fuzzy_search(&s, &list.iter().map(String::as_ref).collect::>()); } }rust-fuzzy-search-0.1.1/src/main.rs000064400000000000000000000044710000000000000153140ustar 00000000000000use rust_fuzzy_search::*; fn main() { fuzzy_compare("kolbaso", "kolbasobulko"); } #[allow(dead_code)] fn simple_search() { let s = "bulko"; let list: Vec<&str> = vec!["kolbasobulko", "sandviĉo"]; let res = fuzzy_search(&s, &list); for x in res { println!("{:?}", x) } } #[allow(dead_code)] fn search_through_file() { use std::fs::File; use std::io::Read; // string to search in the file let input = "colos"; // filename let filename = "src/example_file.txt"; // creates a buffer and reads the file let mut buffer = String::new(); File::open(filename) .unwrap() .read_to_string(&mut buffer) .unwrap(); // split the string in the buffer in words let dict: Vec<&str> = buffer.split(' ').collect(); // gets the n (10usize) best matches let ress = fuzzy_search_best_n(&input, &dict, 10usize); // prints all the matches for (x, d) in ress { println!("word : {:?} \t\t\t\t score : {:?}", x, d); } } #[allow(dead_code)] fn repl_compare() { use std::io; loop { println!("write 2 lines:"); // creates 2 buffers to read from stdin let mut buffer1 = String::new(); let mut buffer2 = String::new(); // reads 2 lines from stdin io::stdin().read_line(&mut buffer1).unwrap(); io::stdin().read_line(&mut buffer2).unwrap(); // test quit instruction (user typed something similar to "quit") if fuzzy_compare(&buffer1, &"quit") > 0.9 { println!("quit : quitting"); break; } // compares strings and prints the score let distance = fuzzy_compare(&buffer1, &buffer2); println!("distance is {:?}", distance); } } #[allow(dead_code)] fn simple_searches() { println!( "bulubulu - bulubulu : {:?}", fuzzy_compare(&"bulubulu".to_string(), &"bulubulu".to_string()) ); println!( "sandviĉo - sandviĉo : {:?}", fuzzy_compare(&"sandviĉo".to_string(), &"sandviĉo".to_string()) ); println!( "sandviĉo - kolbasobulko : {:?}", fuzzy_compare(&"sandviĉo".to_string(), &"kolbasobulko".to_string()) ); println!( "varma vetero - vetero : {:?}", fuzzy_compare(&"varma vetero".to_string(), &"vetero".to_string()) ); }