1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

examples: fix word_counter

This commit is contained in:
ytakahashi 2019-10-16 08:52:37 +09:00 committed by Alexander Medvednikov
parent 1956c6f906
commit c3e1ada405
2 changed files with 33 additions and 12 deletions

View File

@ -1,24 +1,25 @@
``` ```
usage: word_counter [text_file] usage: word_counter [text_file]
using cinderella.txt using cinderella.txt
a => 25
able => 2 able => 2
afterwards => 1
after => 1 after => 1
against => 2 afterwards => 1
again => 10 again => 10
allowed => 2 against => 2
allow => 1
all => 12 all => 12
allow => 1
allowed => 2
along => 1 along => 1
also => 2 also => 2
always => 2 always => 2
an => 4
and => 140 and => 140
anew => 1 anew => 1
anger => 1 anger => 1
another => 2 another => 2
answered => 1 answered => 1
anyone => 2
any => 1 any => 1
an => 4 anyone => 2
... ...
``` ```

View File

@ -18,12 +18,8 @@ fn main() {
return return
} }
mut m := map[string]int mut m := map[string]int
for word in contents.to_lower().split(' ') { for word in extract_words(contents) {
key := filter_word(word) m[word] = m[word] + 1 // TODO m[key]++
if key == '' {
continue
}
m[key] = m[key] + 1// TODO m[key]++
} }
// Sort the keys // Sort the keys
mut keys := m.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 // Removes punctuation
fn filter_word(word string) string { fn filter_word(word string) string {
if word == '' || word == ' ' { if word == '' || word == ' ' {