開発環境
- macOS Mojave - Apple (OS)
- Emacs (Text Editor)
- Windows 10 Pro (OS)
- Visual Studio Code (Text Editor)
- Go (プログラミング言語)
プログラミング言語Go (ADDISON-WESLEY PROFESSIONAL COMPUTING SERIES) (Alan A.A. Donovan(著)、Brian W. Kernighan(著)、柴田 芳樹(翻訳)、丸善出版)の第5章(関数)、5.3(複数戻り値)、練習問題5.5の解答を求めてみる。
コード
package main
import (
"bufio"
"fmt"
"log"
"net/http"
"os"
"strings"
"golang.org/x/net/html"
)
func main() {
url := os.Args[1]
words, images, err := CountWordsAndImages(url)
if err != nil {
log.Fatal(err)
}
fmt.Printf("words: %v, images: %v\n", words, images)
}
func CountWordsAndImages(url string) (words, images int, err error) {
resp, err := http.Get(url)
if err != nil {
return 0, 0, err
}
doc, err := html.Parse(resp.Body)
resp.Body.Close()
if err != nil {
err = fmt.Errorf("parseing HTML: %s", err)
return 0, 0, err
}
words, images = countWordsAndImages(doc)
return words, images, nil
}
func countWordsAndImages(n *html.Node) (words, images int) {
if n.Type == html.TextNode {
reader := strings.NewReader(n.Data)
input := bufio.NewScanner(reader)
input.Split(bufio.ScanWords)
for input.Scan() {
words += 1
}
} else if n.Type == html.ElementNode && n.Data == "img" {
images++
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
w, i := countWordsAndImages(c)
words += w
images += i
}
return words, images
}
入出力結果(Bash、cmd.exe(コマンドプロンプト)、Terminal)
$ go run sample5.go https://www.example.com words: 93, images: 0 $ go run sample5.go https://www.mkamimura.com words: 3950, images: 66 $
0 コメント:
コメントを投稿