如何计算 HTML 文件或 HTML 字符串中的字符数和单词数?

我从 HTML 文件中输入了这个字符串:


<h1> Hello world </h1> 

我想计算这个文件的单词和字符数(不包括 HTML 元素)


例如:


Input 


<h1>Hello</h1>\n<h1>Hello</h1>


Output


Characters : 10

Word : 2

我相信会有一个步骤我们首先解析这个 HTML 内容。但我不知道哪个包支持。


绝地无双
浏览 228回答 1
1回答

慕虎7371278

您可以通过正则表达式找到它们。&nbsp; &nbsp; input := []byte("<h1>Hello</h1>\n<h1>Hello</h1>")&nbsp; &nbsp; tags, _ := regexp.Compile("(\\<\\/?[A-z0-9]+\\>)|(\\\\[A-z]{1})")&nbsp; &nbsp; // remove tags and backslash characters&nbsp; &nbsp; input = tags.ReplaceAll(input, []byte(" "))&nbsp; &nbsp; words, _ := regexp.Compile("[A-z0-9]+")&nbsp; &nbsp; // find all matched words and count them&nbsp; &nbsp; fmt.Println("total words: ", len(words.FindAll(input, -1)))&nbsp; &nbsp; chars, _ := regexp.Compile("[A-z0-9]{1}")&nbsp; &nbsp; // find all matched characters and count them&nbsp; &nbsp; fmt.Println("total characters: ", len(chars.FindAll(input, -1)))&nbsp; &nbsp;&nbsp;输出:total words:&nbsp; 2total characters:&nbsp; 10
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go