-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhtml.go
56 lines (49 loc) · 1.05 KB
/
html.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
package wstat
import (
"bytes"
"errors"
"io"
"golang.org/x/net/html"
)
// IgnoreHTMLTags contains the list of names of the HTML tags, the contents of
// which are ignored.
var IgnoreHTMLTags = map[string]struct{}{
"script": {},
"style": {},
"head": {},
"title": {},
}
// FromHTML extracts text from HTML and returns statistical information on text.
// The contents of the tag from the IgnoreHTMLTAGS list is ignored.
func FromHTML(r io.Reader) (c Counter, err error) {
var ignoreDepth int
z := html.NewTokenizer(r)
for {
tt := z.Next()
switch tt {
case html.ErrorToken:
err = z.Err()
if errors.Is(err, io.EOF) {
err = nil
}
return
case html.TextToken:
if ignoreDepth > 0 {
continue
}
text := z.Text()
if len(bytes.TrimSpace(text)) > 0 {
_, _ = c.Write(text) // only not empty text
}
case html.StartTagToken, html.EndTagToken:
name, _ := z.TagName()
if _, ok := IgnoreHTMLTags[string(name)]; ok {
if tt == html.StartTagToken {
ignoreDepth++
} else {
ignoreDepth--
}
}
}
}
}