60 lines
1.2 KiB
Go
60 lines
1.2 KiB
Go
package main
|
|
|
|
import (
|
|
"bytes"
|
|
"fmt"
|
|
"os"
|
|
"strings"
|
|
|
|
"golang.org/x/net/html"
|
|
)
|
|
|
|
var raw = `
|
|
<!DOCTYPE html>
|
|
<html lang="en">
|
|
<body>
|
|
<div class="node1">
|
|
<img src="/images/node1.png" alt="node one image">
|
|
<p>First node first child</p>
|
|
</div>
|
|
<div class="node2">
|
|
<img src="/images/node2.png" alt="node two image">
|
|
<h1>Second node second child</h1>
|
|
</div>
|
|
<div class="node3">
|
|
<a href="https://example.com">Third node second child</a>
|
|
</div>
|
|
</body>
|
|
</html>
|
|
`
|
|
|
|
func main() {
|
|
doc, err := html.Parse(bytes.NewReader([]byte(raw)))
|
|
if err != nil {
|
|
fmt.Fprintf(os.Stderr, "Parsing failed: %s\n", err)
|
|
os.Exit(-1)
|
|
}
|
|
|
|
words, images := counterofwordsandimages(doc)
|
|
fmt.Printf("There are %d words and %d images\n", words, images)
|
|
}
|
|
|
|
func counterofwordsandimages(doc *html.Node) (int, int) {
|
|
var words, images int
|
|
|
|
visit(doc, &words, &images)
|
|
|
|
return words, images
|
|
}
|
|
|
|
func visit(n *html.Node, words, images *int) {
|
|
if n.Type == html.TextNode {
|
|
*words += len(strings.Fields(n.Data))
|
|
} else if n.Type == html.ElementNode && n.Data == "img" {
|
|
*images++
|
|
}
|
|
for c := n.FirstChild; c != nil; c = c.NextSibling {
|
|
visit(c, words, images)
|
|
}
|
|
}
|