examples: fix word_counter

pull/2369/head
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]
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
...
```

View File

@ -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 == ' ' {