forked from ray-g/gopl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwordimagecounter.go
79 lines (72 loc) · 1.47 KB
/
wordimagecounter.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package main
import (
"bufio"
"fmt"
"io"
"log"
"net/http"
"os"
"strings"
"golang.org/x/net/html"
)
var stdout io.Writer = os.Stdout
var stderr io.Writer = os.Stderr
// CountWordsAndImages does an HTTP GET request for the HTML
// document url and returns the number of words and images in it.
func CountWordsAndImages(url string) (words, images int, err error) {
resp, err := http.Get(url)
if err != nil {
return
}
doc, err := html.Parse(resp.Body)
resp.Body.Close()
if err != nil {
err = fmt.Errorf("parsing HTML: %s", err)
return
}
words, images = countWordsAndImages(doc)
return
}
func countWordsAndImages(n *html.Node) (words, images int) {
u := make([]*html.Node, 0)
u = append(u, n)
for len(u) > 0 {
n = u[len(u)-1]
u = u[:len(u)-1]
switch n.Type {
case html.TextNode:
if n.Parent.Data != "script" && n.Parent.Data != "style" {
words += wordCount(n.Data)
}
case html.ElementNode:
if n.Data == "img" {
images++
}
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
u = append(u, c)
}
}
return
}
func wordCount(s string) int {
n := 0
scan := bufio.NewScanner(strings.NewReader(s))
scan.Split(bufio.ScanWords)
for scan.Scan() {
n++
}
return n
}
func main() {
if len(os.Args) != 2 {
fmt.Fprintf(stderr, "usage: %s URL\n", os.Args[0])
return
}
url := os.Args[1]
words, images, err := CountWordsAndImages(url)
if err != nil {
log.Fatal(err)
}
fmt.Fprintf(stdout, "words: %d\nimages: %d\n", words, images)
}