博客五部曲之二 - 高级博客


1175 浏览 5 years, 3 months

19 文字技术和阅读时间

版权声明: 转载请注明出处 http://www.codingsoho.com/

有时候我们需要统计帖子的字数并预估阅读时间,以提高读者阅读体验。

创建文件posts.utils.py,该文件实现一些应用功能

正则表达式会提取字符个数,然后根据预估的读书速度预估时间,这个方法并不完美,但是对于读者来说,这个足够了。

from django.utils.html import strip_tags
def count_words(html_string):
    # html_string = """
    # <h1> this is a title</h1>
    # """
    word_string = strip_tags(html_string)
    matching_words = re.findall(r'\w', word_string)
    count = len(matching_words)
    return count

def get_read_time(html_string):
    count = count_words(html_string)
    read_time_min = (count/200.0) # assuming 200wpm reading  
    read_time_sec = read_time_min * 60
    read_time = str(datetime.timedelta(seconds=read_time_sec))  
    return read_time

计算阅读时间时,根据字数预估出分钟数,再转换成秒,最好调用datetime库函数timedelta转换成标准时间格式,注释掉的测试代码的阅读时间为0:00:03.600000

注意:预估时间是根据HTML格式进行的,所以调用该函数时我们输入的参数应该是Post的get_markdown()还不是Textfield里面直接读出的内容。

get_read_time(instance.get_markdown())