Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(Soundex): implement soundex algo #5

Merged
merged 2 commits into from
Nov 10, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,5 @@ default = []
dev = ["clippy"]

[dependencies]
itertools = "0.4.3"
clippy = { version = "*", optional = true }
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ Rust-nlp
- [x] Jaro / Jaro-Winkler ([Explanation](https://fr.wikipedia.org/wiki/Distance_de_Jaro-Winkler))

### Phonetics
- [ ] Soundex ([Explanation](https://en.wikipedia.org/wiki/Soundex))
- [x] Soundex ([Explanation](https://en.wikipedia.org/wiki/Soundex))
- [ ] Metaphone ([Explanation](https://en.wikipedia.org/wiki/Metaphone))
- [ ] Double-metaphone ([Explanation](https://en.wikipedia.org/wiki/Metaphone#Double_Metaphone))
- [ ] Caverphone ([Explanation](https://en.wikipedia.org/wiki/Caverphone))
Expand Down
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
#![doc="Natural language processing library"]


#[macro_use] extern crate itertools;

/// Distance module (Levenshtein, Jaro, Jaro-winkler)
pub mod distance;

Expand Down
181 changes: 178 additions & 3 deletions src/phonetics/soundex.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,186 @@
use itertools::Itertools;

#[derive(PartialEq, Hash, Clone, Copy, Debug)]
/// Soundex char mapping
pub enum SoundexChar {
/// B, F, P, V
S1,
/// C, G, J, K, Q, S, X, Z
S2,
/// D, T
S3,
/// L
S4,
/// M, N
S5,
/// R
S6,
/// Vowels
Vowel,
/// H, W
HW,
/// Space
Space,
}

/// Encode a normal char into a soundex char
fn encode(ch: char) -> SoundexChar {
if let Some(c) = ch.to_lowercase().next() {
match c {
'b' | 'f' | 'p' | 'v' => SoundexChar::S1,
'c' | 'g' | 'j' | 'k' | 'q' | 's' | 'x' | 'z' => SoundexChar::S2,
'd' | 't' => SoundexChar::S3,
'l' => SoundexChar::S4,
'm' | 'n' => SoundexChar::S5,
'r' => SoundexChar::S6,
'h' | 'w' => SoundexChar::HW,
' ' => SoundexChar::Space,
_ => SoundexChar::Vowel,
}
} else {
SoundexChar::Vowel
}
}

#[derive(PartialEq, Hash, Clone, Debug)]
/// A soundex word
pub struct SoundexWord {
first_char: char,
soundex_chars: Vec<SoundexChar>,
}

impl SoundexWord {
/// Generate a soundex word base on a string
fn new(word: &str) -> SoundexWord {
let first_char = word
.chars().clone().nth(0)
.unwrap_or('_');

let soundex_chars = word
.chars()
.map(encode)
.skip(1)
.filter(|x| *x != SoundexChar::HW)
.dedup()
.filter(|x| *x != SoundexChar::Vowel)
.collect::<Vec<_>>();

SoundexWord {
first_char: first_char,
soundex_chars: soundex_chars
}
}

/// Convert soundex word to the normal soundex representation
fn to_string(&self) -> String {
self.first_char.to_string() +
&self.soundex_chars.iter().map(|x| {
match *x {
SoundexChar::S1 => "1",
SoundexChar::S2 => "2",
SoundexChar::S3 => "3",
SoundexChar::S4 => "4",
SoundexChar::S5 => "5",
SoundexChar::S6 => "6",
SoundexChar::Space => "",
_ => "_",
}.to_owned()
}).join("")
}
}

/// Try soundex
///
/// Examples:
///
/// ```
/// use nlp::phonetics::soundex::soundex;
/// assert_eq!("SIMON", soundex("SIMON ", ""));
/// assert_eq!("S550", soundex("SIMON "));
/// ```
pub fn soundex(a: &str) -> String {
let soundex_a = SoundexWord::new(a).to_string();

let mut s = String::new();
s.push_str(&soundex_a[..]);

if s.len() < 4 {
for _ in (0..(4 - s.len())).enumerate() {
s.push('0');
}
}

s.truncate(4);
s.to_uppercase()
}

/// Compare soundex words
///
/// Examples:
///
/// ```
pub fn soundex(a: &str, b: &str) -> String {
a.trim().to_uppercase()
/// use nlp::phonetics::soundex::compare_soundex_words;
///
/// assert!(compare_soundex_words("SIMON", "SIMON"));
/// assert!(compare_soundex_words("hey", "hei"));
/// assert!(compare_soundex_words("america", "amurica"));
/// assert!(compare_soundex_words("lol", "lul"));
/// assert!(!compare_soundex_words("purée", "bisous"));
/// assert!(compare_soundex_words("purée", "purée"));
/// ```
pub fn compare_soundex_words(a: &str, b: &str) -> bool {
soundex(a) == soundex(b)
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn soundex_1() {
assert_eq!("S550", soundex("SIMON"))
}

#[test]
fn soundex_2() {
assert_eq!("S553", soundex("Simon TESTing"))
}

#[test]
fn soundex_3() {
assert_eq!("A261", soundex("Ashcroft"))
}

#[test]
fn soundex_4() {
assert_eq!("P600", soundex("purée"))
}

#[test]
fn soundex_5() {
assert_eq!("P300", soundex("putée"))
}

#[test]
fn soundex_6() {
assert!(compare_soundex_words("putée", "putée"))
}

// False positive
#[test]
fn soundex_7() {
assert!(compare_soundex_words("hey rupert", "hei robert"))
}

// False positive
#[test]
fn soundex_8() {
assert!(compare_soundex_words("what's up", "wats oops"))
}

// False positive
#[test]
fn soundex_9() {
assert!(compare_soundex_words("lol your stupid", "lul ur stoupid"))
}

}