python - 如果正文中有html标签,如何创建一个返回博客文章阅读时间的Django模型函数?
问题描述
我正在创建一个 Django 博客,我在 medium 或 dev.to 等博客中看到了平均阅读时间的特性,我问自己如何实现它。
博客/models.py:
class Post(models.Model):
title = models.CharField(max_length=200)
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
header_image = models.ImageField(blank=True, null=True, upload_to="images/post_header/")
date = models.DateField(auto_now_add=True)
description = models.TextField(blank=True, null=True)
category = models.ForeignKey(Category, on_delete=models.CASCADE)
# body = models.TextField()
body = RichTextField()
upvotes = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="post_votes")
def total_likes(self):
"""
Returns total likes in the page
"""
return self.upvotes.count()
def __str__(self):
"""
Show the title and the author in the admin Page
"""
return self.title + " by " + str(self.author)
def get_time_read(self):
return "Some tricky code to get the body of the post and return the words stripping the
tags"
def get_absolute_url(self):
return reverse("blog:article_page", kwargs={"pk": self.pk})
我认为最简单的方法是在 Post 模型中实现一个函数,通过计算总字数并将其除以每分钟的平均字数(大约 200 w/m),返回一个普通成年人的阅读时间,以及之后将函数传递给 html 模板并呈现读取的时间。
这将很容易实现,如果博客文章正文中没有html
标签,因为我在表单中使用富文本编辑器(django-ckeditor)来编写它。
那么如何获取博客文章正文的内容以及如何剥离标签以获取总字数?
解决方案
一种方法是使用诸如 beautiful soup 之类的库来解析您的 html。然后你可以数单词:
from bs4 import BeautifulSoup
WORDS_PER_MINUTE = 100
class Post(models.Model):
...
def get_reading_time(self):
soup = BeautifulSoup(self.body, 'html.parser')
text = soup.get_text()
word_count = len(text.split())
read_time = word_count / WORDS_PER_MINUTE
return read_time
物有所值。这不一定是我会这样做:
想象一下,你正在写一篇关于如何使用 django 的博客。您将在其中包含代码部分。阅读代码需要多长时间?这取决于代码以及您需要考虑多长时间。同样对于任何主题,有些博客的阅读时间更长,与字数无关。
一种方法可能只是将阅读时间添加为必填字段,并要求博客文章作者提供估计的阅读时间。当然,这种方法也有缺点。如果您有很多作者,并且阅读速度不同,那么您整个网站的估计值就会不一致。
有什么要考虑的...
推荐阅读
- docker - 如何使用 id 拉取 docker 镜像?
- swift - linkTextAttributes 不适用于 Swift 中的字体
- javascript - RXJS observable 上的 .pipe() 和 .subscribe() 方法之间的区别
- c# - C#:Listview LargeIcon 视图:消除行之间的空间
- java - 如何使类成员不在线程之间共享(2个浏览器会话)
- c# - 将 xaml 页面作为子对象添加到面板
- c# - 视图中的依赖注入抛出 system.nullreferenceexception
- spring-security - Jhipster + Okta 启用 OIDC 和 Server2Server
- bash - 字符串和模式之间的匹配
- vba - VBA - 使用嵌套公式和自定义变量