首页 > 解决方案 > Django中文件的部分匹配搜索

问题描述

我正在做 cs50 网络课程并在 Django 中工作。

我需要根据用户搜索的关键字来选择 md 文件。如果查询与文件的名称不匹配,则应将用户带到搜索结果页面,该页面显示将查询作为子字符串的所有文件的列表。例如,如果搜索查询是 Py,那么 Python 应该出现在搜索结果中,假设存在这样的文件。

问题是我不确定如何。我们也不使用sql。

这是 util.py,课程给出的代码,我们被告知我们不需要接触:

import re

from django.core.files.base import ContentFile
from django.core.files.storage import default_storage


def list_entries():
    """
    Returns a list of all names of encyclopedia entries.
    """
    _, filenames = default_storage.listdir("entries")
    return list(sorted(re.sub(r"\.md$", "", filename)
                for filename in filenames if filename.endswith(".md")))


def save_entry(title, content):
    """
    Saves an encyclopedia entry, given its title and Markdown
    content. If an existing entry with the same title already exists,
    it is replaced.
    """
    filename = f"entries/{title}.md"
    if default_storage.exists(filename):
        default_storage.delete(filename)
    default_storage.save(filename, ContentFile(content))


def get_entry(title):
    """
    Retrieves an encyclopedia entry by its title. If no such
    entry exists, the function returns None.
    """
    try:
        f = default_storage.open(f"entries/{title}.md")
        return f.read().decode("utf-8")
    except FileNotFoundError:
        return None

这是我的意见功能:

    def entry(request, title): #based on the url it shows a md file
        try:
            content = markdown2.markdown(util.get_entry(title))
        except:
            return HttpResponseNotFound("Page not found")
    
        return render(request, "encyclopedia/entry.html", {
            "entry": content, "title": title.capitalize()
        })
    
    
    def search(request): 
        keyword = request.GET.get('q')
        result = util.get_entry(keyword)
    
        if result:  #if the keyword matches a title, return that result
            content = markdown2.markdown(util.get_entry(result))
            return redirect('entry', result)

        else: #here i should return results that match the substring query
#stuck
            results = util.get_entry('%keyword%')
            return render(request, "encyclopedia/results.html", {
            "results": results
        })

搜索栏:

<form method="get" action="{% url 'search' %}">
{% csrf_token %}
<input type="text" name="q" placeholder="Search Encyclopedia">
</form>

标签: pythondjango

解决方案


您可以通过在 Python 中使用索引来实现这一点。这是我的做法。

list = ["Python", "CSS"]
q = "Py"

for i in list:
    for j in range(3):
        result = str(i[0:j])
        if result == q:
            print("One entry found: ", i)

输出:

找到一个条目:Python


推荐阅读