Python 在不更改字符的情况下查找包含子字符串的列表中的所有名称
我正在一个搜索系统的列表中进行键搜索,但在展览中遇到了一些问题。我发现,如果我将这两个字母都小写,那么包含所有页面标题和键的列表就可以进行简单的搜索。成功了 但最后,为了将搜索到的标题显示为相关结果,我将显示小写的名称,就像我为了比较而做的那样。我想知道是否有任何方法,我可以显示的名称,因为他们之前比较或更好的方式来做这个搜索,寻找保持原来的标题 这是我的搜索功能Python 在不更改字符的情况下查找包含子字符串的列表中的所有名称,python,html,django,list,search,Python,Html,Django,List,Search,我正在一个搜索系统的列表中进行键搜索,但在展览中遇到了一些问题。我发现,如果我将这两个字母都小写,那么包含所有页面标题和键的列表就可以进行简单的搜索。成功了 但最后,为了将搜索到的标题显示为相关结果,我将显示小写的名称,就像我为了比较而做的那样。我想知道是否有任何方法,我可以显示的名称,因为他们之前比较或更好的方式来做这个搜索,寻找保持原来的标题 这是我的搜索功能 def search(request): q = request.GET['q'] if util.get_entr
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 %}
{%extends“encyclopedia/layout.html”%}
{%block title%}
{{title}的搜索结果
{%endblock%}
{%block body%}
“{{title}}”搜索结果
{%endfor%}
{%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,它将创建一个新对象并更改该对象,但不会更改您的项目。您尝试过什么吗?只有在进行比较时才能更改案例。顺便说一句,使用rater可能比使用str.lower()更好。是的。我只是在比较中使用str.lower()得到它,但它也与str.casefold()一起工作,我认为甚至更好。谢谢你的提示!这种改变将在哪里发生?在
所有\u条目中=[item.lower()表示所有\u条目中的项目]
?