python - 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>
解决方案
您可以通过在 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
推荐阅读
- reactjs - React Bootstrap 表未格式化
- pipe - Exim 4.91 - 将所有传入的电子邮件传送到脚本
- php - Typo3升级后,无法将空字符串分配给fluidpages\Classes\Provider\PageProvider.php第193行中的字符串偏移量
- php - JmsSerializerBundle 安装以错误结束:“jms_serializer.visitors”下的无法识别选项“xml”
- c# - c#序列化/反序列化没有时间的日期
- while-loop - 不小心创建了一个永无止境的 while 循环。我现在怎样才能停止我的 SIM 卡?
- angular5 - 如何将组件中的默认值设置为 Mat-select 触发(更改)
- javascript - javascript中for循环内的异步函数
- ruby - 为什么聚合过滤的数据集会丢失它的过滤器?
- amazon-web-services - 是否可以为 AWS 角色信任关系指定模式