解决jekyll函数(number_of_words)中文字数统计错误


解决jekyll函数(number_of_words)中文字数统计错误

Published on July 26, 2023 by Andersen

jekyll

1 min READ

在jekyll中有个内置函数number_of_words,计算当前内容的字数

一般用来计算阅读时间,比如当前内容180字,如果一分钟能够阅读180字则用number_of_words除以180则是读完大概需要的时间.

number_of_words中应该是根据空格计算文章长度,则英文一个单词视为一个字.导致中文统计错误. 原贴

官方已经解决了这个问题,需要再调用时传递额外参数

  • jekyll源码
    # Count the number of words in the input string.
    #
    # input - The String on which to operate.
    #
    # Returns the Integer word count.
    def number_of_words(input, mode = nil)
      cjk_charset = '\p{Han}\p{Katakana}\p{Hiragana}\p{Hangul}'
      cjk_regex = %r![#{cjk_charset}]!o
      word_regex = %r![^#{cjk_charset}\s]+!o

      case mode
      when "cjk"
        input.scan(cjk_regex).length + input.scan(word_regex).length
      when "auto"
        cjk_count = input.scan(cjk_regex).length
        cjk_count.zero? ? input.split.length : cjk_count + input.scan(word_regex).length
      else
        input.split.length
      end
    end
  • 中文使用示例
 { assign words = content | number_of_words:'auto'}