1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
extern crate regex;
extern crate snailquote;
extern crate htmlescape;

pub struct Tokenizer {
    properties : Vec<RegexProperties>,
}

struct RegexProperties {
    str_regex : regex::Regex,
    str_replacement : &'static str,
}

impl Tokenizer {
    pub fn new() -> Tokenizer {
        let mut regexes : Vec<RegexProperties> = Vec::new();
        for reg_format in _DEFAULT_REGEX_FORMAT.iter() {
            regexes.push(RegexProperties{
                str_regex: regex::Regex::new(reg_format.0).unwrap(),
                str_replacement: reg_format.1,
            });
        }
        Tokenizer{
            properties: regexes,
        }
    }

    pub fn tokenize(&self, sentence: &str) -> Vec<String> {
        let mut _cleaned_sentence : String;
        _cleaned_sentence = sentence.to_lowercase();
        _cleaned_sentence = snailquote::unescape(sentence).unwrap();
        _cleaned_sentence = htmlescape::decode_html(&_cleaned_sentence).unwrap();        
    
        for regex_property in &self.properties {
            _cleaned_sentence = regex_property.str_regex.replace_all(&_cleaned_sentence, regex_property.str_replacement).to_string();
        }

        _cleaned_sentence = _cleaned_sentence.trim().to_string();
                
        vec![_cleaned_sentence.split_whitespace().collect()]
    }
}

// don't change the order, this follows the structure of actual algorithm
static _DEFAULT_REGEX_FORMAT: &[(&str, &str)] = &[
    // URL
    (r"(?i)(www\.|https?|s?ftp)\S+", ""),
    
    // email
    (r"(?i)\S+@\S+", ""),

    // twitter
    (r"(?i)(@|#)\S+", ""),

    // escape string
    (r"(?i)&.*;", ""),

    // symbols
    (r"(?i)[^a-z\s]", "")
];