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

huangapple go评论64阅读模式
英文:

How to count number of characters and words in an HTML file or HTML string?

问题

我有一个来自HTML文件的字符串输入:

<h1> Hello world </h1>

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

例如:

输入

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

输出

字符数:10
单词数:2

我相信我们需要先解析这个HTML内容。但是我不知道哪个包支持这个功能。

英文:

I have this string input from a HTML file:

<h1> Hello world </h1> 

I want to count number of word and character of this file (not include HTML element)

For example:

Input 

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

Output

Characters : 10
Word : 2

I believe there will be a step we parse this HTML content first. But I dont know which package support that.

答案1

得分: 2

你可以通过正则表达式找到它们。

input := []byte("<h1>Hello</h1>\n<h1>Hello</h1>")

tags, _ := regexp.Compile(`(\<\/?[A-z0-9]+\>)|(\\[A-z]{1})`)
// 移除标签和反斜杠字符
input = tags.ReplaceAll(input, []byte(" "))

words, _ := regexp.Compile(`[A-z0-9]+`)
// 找到所有匹配的单词并计数
fmt.Println("总单词数:", len(words.FindAll(input, -1)))

chars, _ := regexp.Compile(`[A-z0-9]{1}`)
// 找到所有匹配的字符并计数
fmt.Println("总字符数:", len(chars.FindAll(input, -1)))	

输出:

总单词数: 2
总字符数: 10
英文:

You can find them by regular expression.

	input := []byte(&quot;&lt;h1&gt;Hello&lt;/h1&gt;\n&lt;h1&gt;Hello&lt;/h1&gt;&quot;)

	tags, _ := regexp.Compile(&quot;(\\&lt;\\/?[A-z0-9]+\\&gt;)|(\\\\[A-z]{1})&quot;)
	// remove tags and backslash characters
	input = tags.ReplaceAll(input, []byte(&quot; &quot;))

	words, _ := regexp.Compile(&quot;[A-z0-9]+&quot;)
	// find all matched words and count them
	fmt.Println(&quot;total words: &quot;, len(words.FindAll(input, -1)))

	chars, _ := regexp.Compile(&quot;[A-z0-9]{1}&quot;)
	// find all matched characters and count them
	fmt.Println(&quot;total characters: &quot;, len(chars.FindAll(input, -1)))	

output:

total words:  2
total characters:  10

huangapple
  • 本文由 发表于 2022年5月15日 13:56:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/72245849.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定