简体   繁体   English

如何使 txt 文件的搜索输入不区分大小写

[英]How to make search input case insensitive for txt file

Right now the code is working but if I don't capitalize the first letter of both first and last name the code will return "error: person not found."现在代码正在运行,但如果我不将名字和姓氏的第一个字母大写,代码将返回“错误:找不到人”。

How can I set it up so that no matter how the user inputs the search it will return the requested data?如何设置它以便无论用户如何输入搜索,它都会返回请求的数据?

#Iterate through the lines and save them in a dictionary, with the
#full name as the key
for line in file:
    stripped = line.strip()
    name = stripped[:stripped.index(',')]
    d[name] = stripped[stripped.index(',')+1:].strip()

def main():定义主():

#call the input function to read the file
addresses = input_address()

#Get the user option
option = int(input("Lookup (1) phone numbers or (2) addresses: "))

if option == 1:
    phone = True
else:
    phone = False

#Ask for names and print their information in case they exist, end on blank entry
while True:
    name = input("Enter space-separated first and last name: ")

    if name == "":
        return main()
    if name not in addresses:
        print("Error: person not found")
    else:
        display(addresses[name], phone)

main()主要的()

Try using:尝试使用:

.capitalize()

For example:例如:

'hello world'.capitalize()

yields,产量,

'Hello World'

So in your case, you would do:所以在你的情况下,你会这样做:

name.capitalize()

then look for it inside addresses.然后在地址中查找它。

You can use lower() , upper() , or capitalize() , as long as you attach the chosen method to end of both variables.您可以使用lower()upper()capitalize() ,只要您将所选方法附加到两个变量的末尾即可。

Using lower() :使用lower()

for i in range(len(addresses)):
   addresses[i] = addresses[i].lower()   # Converting array values to lowercase

if name.lower() not in addresses:    # Seeing if lowercase variable is in lowercase array
   print("Error: person not found")
else:
   print("Person found")

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

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