From c3e1ada40500f1d1b855e521c113f5620b018803 Mon Sep 17 00:00:00 2001 From: ytakahashi Date: Wed, 16 Oct 2019 08:52:37 +0900 Subject: [PATCH] examples: fix word_counter --- examples/word_counter/README.md | 13 +++++------ examples/word_counter/word_counter.v | 32 ++++++++++++++++++++++------ 2 files changed, 33 insertions(+), 12 deletions(-) diff --git a/examples/word_counter/README.md b/examples/word_counter/README.md index d21346021..1316ad8b2 100644 --- a/examples/word_counter/README.md +++ b/examples/word_counter/README.md @@ -1,24 +1,25 @@ ``` usage: word_counter [text_file] using cinderella.txt +a => 25 able => 2 -afterwards => 1 after => 1 -against => 2 +afterwards => 1 again => 10 -allowed => 2 -allow => 1 +against => 2 all => 12 +allow => 1 +allowed => 2 along => 1 also => 2 always => 2 +an => 4 and => 140 anew => 1 anger => 1 another => 2 answered => 1 -anyone => 2 any => 1 -an => 4 +anyone => 2 ... ``` diff --git a/examples/word_counter/word_counter.v b/examples/word_counter/word_counter.v index 26bdbd45e..d6c0b951c 100644 --- a/examples/word_counter/word_counter.v +++ b/examples/word_counter/word_counter.v @@ -18,12 +18,8 @@ fn main() { return } mut m := map[string]int - for word in contents.to_lower().split(' ') { - key := filter_word(word) - if key == '' { - continue - } - m[key] = m[key] + 1// TODO m[key]++ + for word in extract_words(contents) { + m[word] = m[word] + 1 // TODO m[key]++ } // Sort the keys mut keys := m.keys() @@ -35,6 +31,30 @@ fn main() { } } +// Creates an array of words from a given string +fn extract_words(contents string) []string { + mut splitted := []string + for space_splitted in contents.to_lower().split(' ') { + if space_splitted.contains('\n') { + splitted << space_splitted.split('\n') + } + else { + splitted << space_splitted + } + } + + mut results := []string + for s in splitted { + result := filter_word(s) + if result == '' { + continue + } + results << result + } + + return results +} + // Removes punctuation fn filter_word(word string) string { if word == '' || word == ' ' { -- 2.30.2