Word Count

1. Readme

字数

给定一个短语,计算该短语中,每个单词的出现次数.

例如输入"olly olly in come free"

olly: 2
in: 1
come: 1
free: 1

资源

这是一个经典的玩具问题,但我们通过在 Go Tour 中,看到它,才想起提醒.

2. 开始你的表演

use std::collections::HashMap;

/// Count occurrences of words.
pub fn word_count(words: &str) -> HashMap<String, u32> {
   unimplemented!("Count of occurrences of words in {:?}", words);
}

3. 测试代码查看


# #![allow(unused_variables)]
#fn main() {
// use std::collections::HashMap;

fn check_word_count(s: &str, pairs: &[(&str, u32)]) {
   // The reason for the awkward code in here is to ensure that the failure
   // message for assert_eq! is as informative as possible. A simpler
   // solution would simply check the length of the map, and then
   // check for the presence and value of each key in the given pairs vector.
   let mut m: HashMap<String, u32> = word_count(s);
   for &(k, v) in pairs.iter() {
       assert_eq!((k, m.remove(&k.to_string()).unwrap_or(0)), (k, v));
   }
   // may fail with a message that clearly shows all extra pairs in the map
   assert_eq!(m.iter().collect::<Vec<(&String, &u32)>>(), vec![]);
}

#[test]
fn test_count_one_word() {
   check_word_count("word", &[("word", 1)]);
}

#[test]
//#[ignore]
fn test_count_one_of_each() {
   check_word_count("one of each", &[("one", 1), ("of", 1), ("each", 1)]);
}

#[test]
//#[ignore]
fn test_count_multiple_occurrences() {
   check_word_count(
       "one fish two fish red fish blue fish",
       &[("one", 1), ("fish", 4), ("two", 1), ("red", 1), ("blue", 1)],
   );
}

#[test]
//#[ignore]
fn test_ignore_punctuation() {
   check_word_count(
       "car : carpet as java : javascript!!&@$%^&",
       &[
           ("car", 1),
           ("carpet", 1),
           ("as", 1),
           ("java", 1),
           ("javascript", 1),
       ],
   );
}

#[test]
//#[ignore]
fn test_include_numbers() {
   check_word_count(
       "testing, 1, 2 testing",
       &[("testing", 2), ("1", 1), ("2", 1)],
   );
}

#[test]
//#[ignore]
fn test_normalize_case() {
   check_word_count("go Go GO Stop stop", &[("go", 3), ("stop", 2)]);
}

#}

4. 答案


# #![allow(unused_variables)]
#fn main() {
use std::collections::HashMap;

pub fn word_count(input: &str) -> HashMap<String, u32> {
   let mut map: HashMap<String, u32> = HashMap::new();
   let lower = input.to_lowercase();
   let slice: &str = lower.as_ref();
   for word in slice
       .split(|c: char| !c.is_alphanumeric())
       .filter(|s| !s.is_empty())
   {
       *map.entry(word.to_string()).or_insert(0) += 1;
   }
   map
}

#}



填充/相关