在不更改字符的情况下查找包含子字符串的列表中的所有名称



我正在搜索系统的列表中进行关键字搜索,但在展览中遇到了一些麻烦。我发现,如果我把两者都小写,我可以简单地搜索包含所有页面标题和关键字的列表。它奏效了。

但最后,为了将搜索到的标题显示为相关结果,我显示了小写的名称,就像我做比较一样。我想知道是否有任何方法可以显示比较前的名称,或者有更好的方法来进行搜索,以保持原始标题。

这是我的搜索功能

def search(request):
q = request.GET['q']
if util.get_entry(q):
#redirect to the existing page calling entry()
return redirect("entry", title=q)
#searching for matching entries titles
#getting all the entries titles in a list
all_entries = util.list_entries()
#lowering case of the list and the key to avoid comparision problems
all_entries = [item.lower() for item in all_entries]
key = q.lower()
#making a new list with the matching results
match_entries = [i for i in all_entries if key in i] 
#renders the results page passing the list of matching titles
return render(request, "encyclopedia/search.html",{
'title' : q,
'entries' : match_entries
})

这是我在HTML 中的搜索页面

{% extends "encyclopedia/layout.html" %}
{% block title %}
Search results for {{ title }}
{% endblock %}
{% block body %}
<h1>"{{ title }}" Search results</h1>
<a>There is no page with the title "{{ title }}"</a>
<ul>
<h2>Similar results:</h2>
{% for entry in entries %}
<a href="{% url 'entry' entry %}"><li>{{ entry }}</li></a>
{% endfor %}
</ul>

{% endblock %}

您还没有提供列表实际包含的内容的示例,但如果您在检查期间只调用.lower()方法,而不是将所有条目都设置为小写,然后执行检查,则它应该可以工作

而不是:

all_entries = [item.lower() for item in all_entries]

你可以使用

#proxy for your line all_entries = util.list_entries()
all_entries=['AaAaA','Baaa','cccccAAA','Dddddaa']
q='AAA'
match_entries=[i for i in all_entries if q.lower() in i.lower()]
['AaAaA', 'Baaa', 'cccccAAA']

您可以使用类似str(item(.lower((的str,它将创建一个新对象并更改该对象,但不会更改您的项。

最新更新