Skip to content

Instantly share code, notes, and snippets.

@Adron
Created July 5, 2019 21:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Adron/3ff88fb9749227f82b964bc0de0a7e2c to your computer and use it in GitHub Desktop.
Save Adron/3ff88fb9749227f82b964bc0de0a7e2c to your computer and use it in GitHub Desktop.
TheCountOfWordsAndImages
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)
}
words, images = countWordsAndImages(doc)
return
}
func countWordsAndImages(n *html.Node) (words, images int) {
if n.Type == html.TextNode {
words += len(strings.Split(n.Data, " "))
return
}
if n.Data == "img" {
images++
} else {
if n.FirstChild != nil {
w, i := countWordsAndImages(n.FirstChild)
words += w
images += i
}
if n.NextSibling != nil {
w, i := countWordsAndImages(n.NextSibling)
words += w
images += i
}
}
return
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment