如何使我的代码对首字母缩略词不敏感

How to make my code insensitive to acronyms

我正在创建一个网站,显示每个大学校园内的可用停车场。如何使代码对首字母缩略词不敏感,e.g.g 如果校园名称是 DCU Alpha?

carparks.html

<h2>
{% if campus %}
{{ campus }}
{% else %}
No such campus
{% endif %}
</h2>
{% if campus %}
{% if carparks %}
<ul>
{% for carpark in carparks %}
<li>{{carpark.name}}: {{carpark.spaces}} spaces, {{carpark.disabled_spaces}} spaces for people with disabilities
  <br>Spaces available:  {{ carpark.spaces_available }}<br><br>
</li>
{% endfor %}
</ul>
{% else %}
<p>No carparks found</p>
{% endif %}
{% endif %}

views.py

def carparks(request):
    context = {}
    Base_URL = 'http://jfoster.pythonanywhere.com/carparks/'
    campus_name = request.GET['campus']
    try:
       campus = Campus.objects.get(name__iexact=campus_name)
    except Campus.DoesNotExist:
       return render(request,"parkatdcu/carparks.html",context)
    carparks = Carpark.objects.filter(campus_id=campus)
    carpark_info = []
    for carpark in carparks:
        URL = Base_URL + carpark.name
        r = requests.get(URL).json()
        if 'spaces_available' in r:
            spaces_available = r['spaces_available']
        else:
            spaces_available = 'not available'
        carpark_info.append({
                         'name': carpark.name,
                         'spaces': carpark.spaces,
                         'disabled_spaces': carpark.disabled_spaces,
                         'spaces_available': spaces_available
                         }
                        )
        context['campus'] = campus_name.title()
        context['carparks'] = carpark_info
        return render(request,"parkatdcu/carparks.html",context)

原始答案:字符串操作

您可以像这样在 python / javascript 中强制使用大写字符串:

python

# becomes DCU ALPHA
'dcu alpha'.upper()
 
# becomes Dcu Alpha
'dcu alpha'.capitalize()

# becomes DCU Alpha: 
'dcu alpha'.split(' ')[0].upper() + ' ' + 'dcu alpha'.split(' ')[1].captialize()

javascript

// becomes DCU ALPHA:
'dcu alpha'.toUpperCase()

// becomes DCU Alpha:
'dcu alpha'.slice(0, 5).toUpperCase() + 'dcu alpha'.slice(5,)

编辑:条件格式:

假设我们有这样的校园名称:

campuses = ['dcu alpha', 'northridge', 'lsu univiersity', 'princeton', ...]

我们可以添加一些逻辑来检查带有首字母缩略词的校区:

views.py

# check if a campus contains two words:
if len(campus_name.split(' ')) > 1: 
    # campus name has at least two words
else: 
    # campus name has only one word

我们还可以创建两个列表,一个包含带有首字母缩略词的校区名称,另一个包含没有首字母缩写词的校区名称:

# set two lists:
campuses_with_acronyms = ['dcu alpha', 'lsu univiersity', ...]
campuses_without_acronyms = ['northride', 'princeton', ...]

# check if the campus name is in either list:
if campus_name in campuses_with_acronyms:
    # campus name has an acronym
else:
    # campus name does not have an acronym