use std::collections::HashMap;
use std::sync::Mutex;
use fancy_regex::Regex;
use once_cell::sync::Lazy;
static RULES: Lazy<Vec<(Regex, &'static str)>> = Lazy::new(|| {
let raw: &[(&str, &str)] = &[
("(?<=a)(mp|nd|nt)s?$", "n"), (r"([aeiouy])mp(?=[^aeiouyr])", "${1}n"), (r"ngt(?=[aeiouy])", "nt"), (r"ngt", "n"), ("((?<=[^g])g|^g)(?=[eyi])", "j"),
("(?<=g)u(?=[aeio])", ""),
(r"(?<=ei)gn([aeiouy])", "ni${1}"), (r"je([aeiouy])", "j${1}"), ("c(?=[^hieyw])", "k"),
(r"anc$", "an"), ("((?<=[^s])ch|(?<=[^0-9])c)$", "k"),
("(?<=[aeiouy])s(?=[aeiouy])", "z"),
("((?<=[^0-9])q|^q)u?", "k"),
("cc(?=[ie])", "s"),
("ck", "k"),
("ph", "f"),
("th$", "te"),
("(?<=[^sc0-9])h", ""),
("^h(?=.)", ""),
("sc", "s"),
("sh", "ch"),
("((?<=[^0-9])w|^w)", "v"),
("c(?=[eiy])", "s"),
(r"((?<=[^0-9])y|^y)", "i"),
("esn", "en"),
(r"eim( |$)", "aim"), (r"(ae|ei)(?=\w)", "e"),
(r"oeufs( |$)", "eu"),
(r"oeu?(?=\w)", "eu"),
("(?<=[^0-9])s$", ""),
("(?<=u)l?x$", ""), ("(?<=u)lt$", "t"),
("(?<=[a-z])[dg]$", ""),
("(?<=[^es0-9])t$", ""),
("(?<=[aeiou])(m)(?=[pbgft])", "n"), ("(?<=[a-z]{2})(e$)", ""),
(r"(?<=[aeiouy])n[dt](?=[^aeiouyr])", "n"), (r"([a-z])\1+", "${1}"), ];
raw.iter()
.map(|(pattern, repl)| {
let re = Regex::new(pattern).unwrap_or_else(|e| panic!("phonemicize {pattern:?}: {e}"));
(re, *repl)
})
.collect()
});
static CACHE: Lazy<Mutex<HashMap<String, String>>> = Lazy::new(|| Mutex::new(HashMap::new()));
pub fn phonemicize(s: &str) -> String {
if let Some(hit) = CACHE.lock().unwrap().get(s) {
return hit.clone();
}
let mut out = s.to_string();
for (re, repl) in RULES.iter() {
out = re.replace_all(&out, *repl).into_owned();
}
CACHE.lock().unwrap().insert(s.to_string(), out.clone());
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn matches_addok_fr() {
let cases = [
("cergy", "serji"),
("conflans", "konflan"),
("dunkerque", "dunkerk"),
("wardrecques", "vardrek"),
("sault", "sau"),
("vaux", "vau"),
("guyancourt", "guiankour"),
("hazebrouck", "azebrouk"),
("vallee", "vale"),
("champs", "chan"),
("vingt", "vin"),
("vingtieme", "vintiem"),
("blanc", "blan"),
("georges", "jorj"),
("seigneur", "senieur"),
("pforzheim", "pforzaim"),
("montbon", "monbon"),
("10a", "10a"),
];
for (input, expected) in cases {
assert_eq!(phonemicize(input), expected, "phonemicize({input:?})");
}
}
}