如何计算 HTML 文件或 HTML 字符串中的字符数和单词数?
How to count number of characters and words in an HTML file or HTML string?
我从 HTML 文件中输入了这个字符串:
<h1> Hello world </h1>
我想统计这个文件的字数和字符数(不包括HTML元素)
例如:
Input
<h1>Hello</h1>\n<h1>Hello</h1>
Output
Characters : 10
Word : 2
我相信会有一个步骤我们首先解析这个HTML内容。但是我不知道哪个包支持。
您可以通过正则表达式找到它们。
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
我从 HTML 文件中输入了这个字符串:
<h1> Hello world </h1>
我想统计这个文件的字数和字符数(不包括HTML元素)
例如:
Input
<h1>Hello</h1>\n<h1>Hello</h1>
Output
Characters : 10
Word : 2
我相信会有一个步骤我们首先解析这个HTML内容。但是我不知道哪个包支持。
您可以通过正则表达式找到它们。
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