2019-06-23 04:21:30 +02:00
|
|
|
// Copyright (c) 2019 Alexander Medvednikov. All rights reserved.
|
|
|
|
// Use of this source code is governed by an MIT license
|
|
|
|
// that can be found in the LICENSE file.
|
|
|
|
|
2019-06-22 20:20:28 +02:00
|
|
|
import os
|
|
|
|
|
|
|
|
fn main() {
|
2019-06-28 15:24:46 +02:00
|
|
|
mut path := 'cinderella.txt'
|
2019-06-22 20:20:28 +02:00
|
|
|
if os.args.len != 2 {
|
|
|
|
println('usage: word_counter [text_file]')
|
|
|
|
println('using $path')
|
|
|
|
}
|
|
|
|
else {
|
|
|
|
path = os.args[1]
|
|
|
|
}
|
2019-06-26 18:01:31 +02:00
|
|
|
contents := os.read_file(path.trim_space()) or {
|
|
|
|
println('failed to open $path')
|
|
|
|
return
|
|
|
|
}
|
2019-06-22 20:20:28 +02:00
|
|
|
mut m := map[string]int{}
|
2019-06-23 06:38:36 +02:00
|
|
|
for word in contents.to_lower().split(' ') {
|
|
|
|
key := filter_word(word)
|
|
|
|
if key == '' {
|
|
|
|
continue
|
2019-06-22 20:20:28 +02:00
|
|
|
}
|
2019-06-23 06:38:36 +02:00
|
|
|
m[key] = m[key] + 1// TODO m[key]++
|
2019-06-22 20:20:28 +02:00
|
|
|
}
|
|
|
|
// Sort the keys
|
2019-07-14 22:26:21 +02:00
|
|
|
mut keys := m.keys()
|
2019-06-22 20:20:28 +02:00
|
|
|
keys.sort()
|
|
|
|
// Print the map
|
|
|
|
for key in keys {
|
|
|
|
val := m[key]
|
|
|
|
println('$key => $val')
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Removes punctuation
|
|
|
|
fn filter_word(word string) string {
|
|
|
|
if word == '' || word == ' ' {
|
|
|
|
return ''
|
|
|
|
}
|
|
|
|
mut i := 0
|
|
|
|
for i < word.len && !is_letter(word[i]) {
|
|
|
|
i++
|
|
|
|
}
|
|
|
|
start := i
|
|
|
|
for i < word.len && is_letter(word[i]) {
|
|
|
|
i++
|
|
|
|
}
|
|
|
|
end := i
|
|
|
|
return word.substr(start, end)
|
|
|
|
}
|
|
|
|
|
|
|
|
// TODO remove once it's possible to call word[i].is_letter()
|
|
|
|
fn is_letter(c byte) bool {
|
|
|
|
return c.is_letter()
|
|
|
|
}
|
|
|
|
|