-
Notifications
You must be signed in to change notification settings - Fork 0
/
words.go
49 lines (39 loc) · 1.34 KB
/
words.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package words
import (
"path/filepath"
_ "github.com/oytuntez/go-words/counters/all"
"github.com/oytuntez/go-words/counters/interface"
"github.com/oytuntez/go-words/counters/registry"
)
// Package struct. Provides File and Text methods.
type Words struct {}
// Detects the type of a file by extension.
// This is used in File function to match related word counters under `counters` directory (and registry)
func (w *Words) detectType(p string) string {
if p == "" {
panic("Please provide file path.")
}
// Extension includes dot: ".csv"
var extension = filepath.Ext(p)
if len(extension) > 0 {
// Remove the leading dot
extension = extension[1:len(extension)]
} else {
panic("No extension.")
}
return extension
}
// Takes a file path and returns the word count by using related word counter for this file type.
// If a counter for this file type is not available, falls back to default counter, which is `base` package.
func (w *Words) File(p string) int {
var fileType string = w.detectType(p)
var counter interfaces.CounterInterface = registry.Get(fileType)
var wordCount int = counter.File(p)
return wordCount
}
// Takes a string and returns the word count by using Txt counter.
func (w *Words) Text(s string) int {
var counter interfaces.CounterInterface = registry.Get("txt")
var wordCount int = counter.Text(s)
return wordCount
}