Skip to content

Instantly share code, notes, and snippets.

@Miezhiko
Last active June 16, 2020 13:10
Show Gist options
  • Save Miezhiko/6d02ccdc592254f393aa2a0480364d9a to your computer and use it in GitHub Desktop.
Save Miezhiko/6d02ccdc592254f393aa2a0480364d9a to your computer and use it in GitHub Desktop.
Words counter
extern crate unicase;
use std::{
collections::HashMap,
iter::FromIterator,
fs
};
use unicase::Ascii;
pub fn main() {
let big_string = fs::read_to_string("file.txt").unwrap();
let mut words_counter: HashMap<Ascii<&str>, u32> = HashMap::new();
for word in big_string.split(&[' ',',','.',';',':','\n','\r'][..]) {
if word.is_empty() { continue; }
let strx = Ascii::new(word);
match words_counter.get_mut(&strx) {
Some(cx) => *cx += 1,
None => { words_counter.insert(strx, 1); }
};
}
let mut vec_from_iter = Vec::from_iter(words_counter);
vec_from_iter.sort_by(|&(_, a), &(_, b)| b.cmp(&a));
let top_x : Vec<String> =
vec_from_iter.into_iter().take(5)
.map(|(k, v)| format!("{} : {}", k, v))
.collect();
print!("{}", top_x.join("\n").as_str());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment