简体   繁体   English

在字典上强制使用大小写以比较Python中的用户输入

[英]Force case on dictionary to compare user input in Python

I'm making a user input decision tree and I want to force the dictionary that the input is being compared to into lowercase. 我正在制作用户输入决策树,我想强制将要比较输入的字典转换为小写形式。 I've placed .lower() at various points and keep getting errors. 我在各个地方放置了.lower()并不断出错。

not_found = True
while True:
    if OPTIONS == "1" or 'a':
        ARTIST_PICK = str(raw_input(
            "Please pick an artist\n"
            "Or Q to quit: ")).lower
        print ARTIST_PICK

        **entries = allData(filename).data_to_dict()
        for d in entries:
            arts = d['artist']**

        if ARTIST_PICK in arts:
            print "found it"

        elif ARTIST_PICK == 'q':
            break

        else:
            print "Sorry, that artist could not be found. Choose again."
            not_found = False

This is a sample of the "entries" I'm trying to make lower and compare the user input to: 这是我要降低的“条目”样本,并将用户输入与以下内容进行比较:

[{'album': 'Nikki Nack', 'song': 'Find a New Way', 'datetime': '2014-12-03 09:08:00', 'artist': 'tUnE-yArDs'},]

If your problem was just comparing the artist names, then you could use list comprehension to make everything lowercase. 如果您的问题只是比较艺术家的姓名,则可以使用列表推导使所有内容变为小写。

entries = allData(filename).data_to_dict()

if ARTIST_PICK in [ d['artist'].lower() for d in entries ]:
    print("found it")
elif ARTIST_PICK == "q":
    break
else
    print("Sorry, that artist could not be found. Choose again.")

Or if you'd rather use a for loop (rearranged a little for readability): 或者,如果您更喜欢使用for循环(为便于阅读而for了一些重新安排):

if(ARTIST_PICK != 'q'):
    entries = allData(filename).data_to_dict()

    found = False

    for d in entries:
        if ARTIST_PICK == d['artist'].lower():
            found = True
            break
        elif ARTIST_PICK == "q":
            break

    if(found):
        print("found it")
    else:
        print("Sorry, that artist could not be found. Choose again.")
else:
    # handle the case where the input is 'q' here if you want

By the way, as a matter of principle you should name your boolean variables as though you were using them in a sentence. 顺便说一句,原则上,您应该将布尔变量命名为好像在句子中使用它们一样。 Instead of setting a variable not_found to False if the variable isn't found, set a variable named found to False or set not_found to True . 如果找不到变量,则不要将变量not_found设置为False而是将名为found的变量设置为False或将not_found设置为True Makes things easier in the long run. 从长远来看使事情变得容易。

ARTIST_PICK = str(raw_input(“请选择一个艺术家\\ n”“或Q退出:”))。lower()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM