Created
July 5, 2019 21:59
-
-
Save Adron/3ff88fb9749227f82b964bc0de0a7e2c to your computer and use it in GitHub Desktop.
TheCountOfWordsAndImages
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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