How to calculate the number of times a specific keyword appears in a string or array?

Calendar 👁️ 97

In the practice of AnQiCMS content management, we often need to perform refined analysis and optimization of website content.Among them, calculating the number of times a specific keyword appears in an article, title, or dataset is a basic and important requirement.In order to evaluate the SEO keyword density, analyze the content quality, or conduct data statistics, AnQiCMS provides a convenient and efficient solution.This article will delve into how to easily achieve this goal by using the built-in features of AnQiCMS.

Core Tool:countFilter parsing

AnQiCMS provides a template engine namedcountThe practical filter, which is the core tool for us to solve the problem of keyword frequency statistics.countThe filter design is simple and can efficiently count the frequency of a specified keyword in a string or array (slice/array).

Its basic usage is very intuitive:

{{ obj|count:关键词 }}

HereobjRepresents the string or array you want to count, and关键词is the text you want to count the occurrences of.

Count keywords in a string

When we want to count the number of times a keyword appears in a text, we can pass the text variable directly tocountthe filter. It is worth noting that,countThe filter matches strings usingexact word matchlogic. This means it will look for substrings that are exactly the same as the keywords you provide.

For example, if you have a text “Welcome to AnQiCMS (AnQiCMS), AnQiCMS is a good helper for your content management,” and you want to count the number of occurrences of the keyword “CMS”:

{% set myString = "欢迎使用安企CMS(AnQiCMS),AnQiCMS是您内容管理的好帮手。" %}
{{ myString|count:"CMS" }}

This code will return2because it found two exact matches for "CMS".

Count keywords in the array

countThe filter applies to array data types. In an array, it will iterate over each element and check if the element matches the keyword you provideentirely equal.

Assuming we have an array composed of string elements, such as throughsplitorfieldsa filter splits a text into a list of words:

{% set sentence = "AnQiCMS provides efficient and customizable content management solutions." %}
{% set wordsArray = sentence|fields %} {# fields 过滤器将字符串按空格拆分成数组 #}
{{ wordsArray|count:"content" }}

Here, wordsArrayit will befieldsprocessed by the filter["AnQiCMS", "provides", "efficient", "and", "customizable", "content", "management", "solutions."]Then,{{ wordsArray|count:"content" }}will return1It found an array element that matches 'content' completely.

It should be emphasized that the array count is still full-word matching. If there is 'AnQiCMS' in the array and you try to count 'AnQi', the result will be0Because 'AnQi' did not appear as an independent element.

Application scenarios: Make data analysis more accurate.

UnderstoodcountAfter learning the basic usage of the filter, let's take a look at its specific application in AnQiCMS template development and content management.

  1. Keyword density analysis of the article contentOn the article detail page, we often need to evaluate the keyword density of the article content, which is crucial for SEO optimization.We can obtain the main content of the article and then count the number of occurrences of specific keywords.

    First, througharchiveDetailTag to retrieve article content:

    {% archiveDetail articleContent with name="Content" %}
    

    Then, we can usecountto count with filters:

    {% set keywordToCount = "AnQiCMS" %} {# 你想统计的关键词 #}
    <p>关键词 "{{ keywordToCount }}" 在文章中出现了 {{ articleContent|count:keywordToCount }} 次。</p>
    
  2. Title and description keyword checkTo ensure that the website's title (Title) and description (Description) comply with SEO strategies, we can quickly check the presence of specific keywords within them.

    {% archiveDetail articleTitle with name="Title" %}
    {% archiveDetail articleDescription with name="Description" %}
    {% set seoKeyword = "内容管理" %} {# 假设要检查的SEO关键词 #}
    
    <p>标题中 "{{ seoKeyword }}" 出现次数:{{ articleTitle|count:seoKeyword }}</p>
    <p>描述中 "{{ seoKeyword }}" 出现次数:{{ articleDescription|count:seoKeyword }}</p>
    
  3. Count of specific identifier in list dataIn certain specific scenarios, for example, if you have an array composed of specific identifiers (such as tag ID lists, product attribute code lists), and you need to count the occurrences of a specific identifier,countThe filter can also play a role.

    For example, if you have a variable namedproductTagsArray containing multiple product tag names:

    {% set productTags = ["电子产品", "智能家居", "手机", "电子产品", "配件"]|list %} {# 假设这是一个动态生成的标签数组 #}
    <p>“电子产品”标签出现的次数:{{ productTags|count:"电子产品" }}</p>
    

Read more: Related search and processing techniques

exceptcountFilter, AnQiCMS also provides other practical filters related to keyword search and string processing, which can be used withcountUse together, or as an alternative in different scenarios.

  • containFilterIf you only need to know whether a string or array 'contains' a certain keyword, without concerning about how many times it appears,containThe filter will be more concise and efficient, it will return a boolean value (True or False).
  • indexFilterIf you want to know the first occurrence position of a keyword (in a string or array index) in addition to knowing whether the keyword exists,indexThe filter will be your choice.
  • splitandfieldsFilterThese two filters can split strings using a specified delimiter (split) or by spaces (fields) split into an array. In some scenarios that require a finer granularity of word statistics (especially for non-Chinese words), you can first split the text into a word array using them and then combinecountThe filter performs statistics.

Summary

AnQiCMS, with its flexible template tags and rich built-in filters, provides powerful data processing capabilities for website content operators.countThe filter acts as an efficient keyword statistics tool, which can help us analyze content deeply, optimize SEO strategies, and better understand and manage website content.Mastery of these tools will make your content operation work more skillful.


Frequently Asked Questions (FAQ)

  1. countDoes the filter support fuzzy matching or partial matching? countThe filter uses strict counting when counting strings and arrays.exact word match(or full element match). It does not perform fuzzy matching or partial matching. For example, if you count "AnQiCMS", and the text only has "AnQi", countIt will return 0. If you need to implement fuzzy matching, you may need to combine other methods, such as using first.splitSplit the text into words, then traverse the array for regular expression matching or partial inclusion judgment, but the AnQiCMS template itself does not support direct regular expression matching.

  2. How to count the number of occurrences of multiple different keywords in a text?To count the number of occurrences of multiple keywords, you need to use each keyword separately.countFilter. For example, to count the occurrences of 'AnQiCMS' and 'Content Management' in a text, you can do this: “`twig {% set text = “AnQiCMS is a powerful content management system, AnQiCMS helps you manage content efficiently. “” %

Related articles

How to determine if a string or array contains a specific keyword?

In AnQi CMS, efficiently identify key information in content: string and array keyword judgment techniques As a content operator, we often need to handle a large amount of text data, from article titles, content descriptions to custom fields, rich and diverse information.In order to optimize search engine (SEO), implement content intelligent recommendation, or perform simple data validation, quickly judge whether a string or array contains a specific keyword is a very practical and efficient skill.In the flexible and powerful template system of Anqi CMS, this task becomes effortless.Utilize built-in filters

2025-11-09

How to center or align a string to a specified length?

When building website content, we often need to fine-tune the text layout to ensure that the information presented is both beautiful and clear.Whether it is a list, table, product parameters, or other structured display data, maintaining visual alignment and consistency is crucial for improving user experience.Aq CMS, known for its high flexibility and ease of use as a content management system, deeply understands the importance of content presentation and has built a series of powerful template filters to help us easily align and center strings

2025-11-09

How to format a floating-point number to a specified number of decimal places?

How to accurately control the decimal places of floating-point numbers in AnQiCMS?In website content operations, we often encounter situations where we need to display prices, statistical data, measurement results, and other floating-point numbers.However, the original floating-point numbers often have unnecessary decimal places, which not only affects the appearance but may also reduce the readability of the data.AnQiCMS fully considers this user's needs, providing flexible and powerful template filters to help us easily implement the formatting of floating-point numbers, making data display more professional and accurate.### Use `floatformat`

2025-11-09

How to get the length of a string, array, or object?

When managing website content in AnQi CMS, we often need to flexibly adjust the page display according to the number of elements in a string, array, or collection.Whether it is to judge whether the length of the article title needs to be truncated, or to count how many documents are under a certain category, or to display the number of user comments, obtaining the 'length' of this content is the key to dynamic display and logical judgment.The AnQi CMS template engine provides built-in features that are simple and efficient, helping us easily deal with these scenarios.Among them, the `length` filter is a powerful assistant for obtaining the length of strings, arrays, or key-value pairs

2025-11-09

How to remove specific characters or HTML tags from a string?

In the daily content operation of AnQiCMS, we sometimes encounter situations where we need to finely process the content, such as removing specific characters, extra spaces, or stripping unnecessary HTML tags from the content.These operations are very critical for ensuring the neatness of content display, adapting to different front-end styles, and even for data cleaning.The AnQi CMS provides powerful template filter functions to help us efficiently complete these tasks.###

2025-11-09

How to split a string into an array with a specified separator?

In the daily operation of AnQi CMS, we often encounter the need to process some data stored as strings but actually containing multiple values.For example, an article may store multiple keywords in a comma-separated manner, or a custom content field may need to support multiple options, and these options are ultimately connected into a string with a specific symbol.In this case, we often need to split these strings using the preset delimiter into independent segments so that they can be displayed flexibly on the page or further processed.AnQi CMS based on the efficient architecture of Go language

2025-11-09

How to concatenate array elements into a string with a specified separator?

When operating a website, we often encounter the need to display a set of related data in the form of a list, such as multiple tags for articles, multiple keywords for product features, or multiple image URLs in an image library.At this time, if these scattered data elements can be integrated into a concise string and separated by specific symbols, it will greatly enhance the display effect and readability of the content.The Anqi CMS template engine provides a very practical `join` filter, which can easily meet this requirement.Understanding the `join` filter `join`

2025-11-09

How to implement automatic line break display for long text?

In website content operation, we often encounter situations where we need to display a large amount of text. If these long texts are not handled properly, they may exceed the designed container, causing chaos in page layout and severely affecting user experience.AnQi CMS provides us with flexible and powerful template functions, which can easily solve the display problem of long text, especially for automatic line breaks.### Core Strategy: Using the `wordwrap` filter to implement automatic text wrapping The template system of Anqi CMS is built-in with many practical filters (Filters), among which

2025-11-09