【问题标题】:Count most used words from Django Model计算 Django 模型中最常用的单词
【发布时间】:2019-06-07 16:49:03
【问题描述】:

我得到了带有 BeautifulSoup 的基本 Django 应用程序,它获取有关作者和内容的数据,然后将其保存到数据库中。我需要从该内容模型中获取前 10 个最常用的词。我知道如何从 url 源中获得前 10 名,但我必须从 Model 中获得,谁能帮助我了解这背后的想法?

    views.py
    .............
    for i in posts:
    link = i.find_all('a', {'class': 'blog-button post-read-button post-button-animation'})[0]
    url = link.get('href')  # getting the url of each post
    fixed_url = '######' + url
    content = session.get(fixed_url, verify=False).content
    soup = BeautifulSoup(content, "lxml")
    author = soup.find_all('span', {'class': 'author-name'})[0].text  # getting the author name
    description = soup.find_all('div', {'class': 'post-content'})[0].text  # getting the content of post
    try:
        a = Author.objects.get(name=author)
    except Author.DoesNotExist:
        author_name = author
        author = Author.objects.create(name=author_name)
        author.save()
    Content.objects.get_or_create(description=description, author=a)
    ..............
    models.py
    class Author(models.Model):
        name = models.CharField(max_length=300)

        def __str__(self):
            return self.name


    class Content(models.Model):
        description = models.TextField()
        author = models.ForeignKey(Author, on_delete=models.CASCADE)

            def __str__(self):
                return self.description

【问题讨论】:

  • 先写一些代码,如果不能解决就贴出来
  • 你能展示一下模型的样子吗?
  • 添加了代码。
  • 内容模型描述中最常用的10个词?
  • 是的,描述中最常用的 10 个词 @hancho

标签: python django beautifulsoup


【解决方案1】:

好的,根据我在 cmets 中的理解,您想要 Content 描述中最常用的 10 个单词。

创建一个方法,将内容拆分为单词列表并遍历该列表,并使用字典来跟踪单词出现的次数。

class Content(models.Model):
...
...
# Add this method to class
def get_most_used_words(self, count):
    words = {}
    description = self.description.split()
    for word in description:
        if word in words:
            words[word] += 1
        else:
            words[word] = 1
    top_10_words = sorted(words.items(),key=lambda x:-x[1])[:count]
    return top_10_words

你现在可以像这样使用上面的方法了

c = Content.objects.last() # Get the last content
print(c.get_most_used_words(10)) # Get the top 10 most used words

【讨论】:

  • 效果很好!但是,如果我想将所有内容模型中的前 10 名放入一个字典中怎么办?
  • 嗨,您能否将此答案标记为已接受,因为它回答了您的问题。至于您的其他问题,请先尝试自己解决,如果无法解决,请尝试在此处发布问题。如果您需要提示,您可以创建一个空字典,遍历您的内容并将每个内容添加到字典中。
猜你喜欢
  • 2014-08-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多