我试图使下面的代码不区分大小写,但不起作用。
如果我尝试加载确切名称!ping george
的工作原理,但是如果我尝试混合使用较高或较低的!ping George
机器人,则不会回复。
@bot.command(pass_context=True)
async def ping(ctx, namesList):
with open('data.json') as json_file:
d = json.load(json_file)
for p in d['people']:
if(p['Name'] in (namesList)):
await bot.send_message(ctx.message.channel, p)
我将此if(p['Name'] in (list)):
更改为if(p['Name'].lower() in (list)):
仍然无法正常工作,我认为我在这行中做错了。
根据评论编辑:
namesList # from json file names contains with upper lower mixed.
some names contain numbers, and some names have space between name and sir name.
data.json sample
{"people": [
{"UserID": "xxxxx123", "Name": "Steve", "Sex": "Male", "age": "30"},
{"UserID": "xxxxx124", "Name": "Rachel", "Sex": "Female", "age": "25"},
{"UserID": "xxxxx125", "Name": "George", "Sex": "Male", "age": "22"} ] }
答案 0 :(得分:1)
您可以创建一个set()小写名称,并在其中查找您的p["Name"]
:
@bot.command(pass_context=True)
async def ping(ctx, namesList):
# sets are better for lookups. prepare a set with all lower case names
setOfNamesLowerCase = set ( x.lower() for x in namesList ) # dont name lists list
with open('data.json') as json_file:
d = json.load(json_file)
for p in d['people']:
if(p['Name'].lower() in setOfNamesLowerCase ):
await bot.send_message(ctx.message.channel, p)
集合更适合此任务,查找值为O(1),如果有重复,它们会自动减少。
在输入正确的情况下,简化了逻辑以检查它是否应该工作:
def find_tata(namesList):
# sets are better for lookups. prepare a set with all lower case names
setOfNamesLowerCase = set ( x.lower() for x in namesList ) # dont name lists list
if "tata" in setOfNamesLowerCase:
print("Its in")
else:
print ("Its not")
find_tata( ["not in here","not in"])
find_tata( ["not in here","tata"])
输出:
Its not
Its in
编辑2:
import json
js = """{"people": [
{"UserID": "xxxxx123", "Name": "Steve", "Sex": "Male", "age": "30"},
{"UserID": "xxxxx124", "Name": "Rachel", "Sex": "Female", "age": "25"},
{"UserID": "xxxxx125", "Name": "George", "Sex": "Male", "age": "22"} ] }"""
def ping(namesList):
# sets are better for lookups. prepare a set with all lower case names
setOfNamesLowerCase = set ( x.lower() for x in namesList ) # dont name lists list
d = json.loads(js)
for p in d['people']:
if(p['Name'].lower() in setOfNamesLowerCase ):
print("Doing smth for ", p["Name"])
ping(["rachEl", "ludwig", "ernie", "GEoRgE"])
输出:
Doing smth for Rachel
Doing smth for George