我從 HTML 文件中輸入了這個字符串:<h1> Hello world </h1> 我想計算這個文件的單詞和字符數(不包括 HTML 元素)例如:Input <h1>Hello</h1>\n<h1>Hello</h1>OutputCharacters : 10Word : 2我相信會有一個步驟我們首先解析這個 HTML 內容。但我不知道哪個包支持。
1 回答

慕虎7371278
TA貢獻1802條經驗 獲得超4個贊
您可以通過正則表達式找到它們。
input := []byte("<h1>Hello</h1>\n<h1>Hello</h1>")
tags, _ := regexp.Compile("(\\<\\/?[A-z0-9]+\\>)|(\\\\[A-z]{1})")
// remove tags and backslash characters
input = tags.ReplaceAll(input, []byte(" "))
words, _ := regexp.Compile("[A-z0-9]+")
// find all matched words and count them
fmt.Println("total words: ", len(words.FindAll(input, -1)))
chars, _ := regexp.Compile("[A-z0-9]{1}")
// find all matched characters and count them
fmt.Println("total characters: ", len(chars.FindAll(input, -1)))
輸出:
total words: 2
total characters: 10
- 1 回答
- 0 關注
- 210 瀏覽
添加回答
舉報
0/150
提交
取消