[英]How do I list specific words it finds in the order it finds them in
I'm creating a discord bot and was wondering how I could list out the words in order it finds them in?我正在创建一个 discord 机器人,我想知道如何列出单词以便找到它们?
item_dict = {
"okay": ("Mythical", "50000"),
"hello": ("Mythical", "17500"),
"hi": ("Legendary", "14500"),
"good": ("Legendary", "11600"),
"very bad": ("Common", "1"),
}
msg = input("Enter ")
new_list = []
for x in item_dict:
if x in msg:
new_list.append(x)
print(new_list)
If for example I enter 4 hi 3 very bad good
, I would want it to check the string and check if it matches any of the items in the dictionary and make it print [hi, very bad, good]
instead of how its ordered in the dictionary which would print out [hi, good, very bad]
.例如,如果我输入
4 hi 3 very bad good
,我希望它检查字符串并检查它是否与字典中的任何项目匹配并使其打印[hi, very bad, good]
而不是它的排序方式会打印出[hi, good, very bad]
的字典。
Sort new_list
with a lambda
, with the key
being the position the word is found in msg
.使用
new_list
对lambda
进行排序, key
是 position 该词在msg
中找到。
Code:代码:
item_dict = {
"okay": ("Mythical", "50000"),
"hello": ("Mythical", "17500"),
"hi": ("Legendary", "14500"),
"good": ("Legendary", "11600"),
"very bad": ("Common", "1"),
}
msg = input("Enter ")
new_list = []
for x in item_dict:
if x in msg:
new_list.append(x)
new_list.sort(key=lambda x: msg.find(x))
print(new_list)
Output: Output:
Enter进入
4 hi 3 very bad good
['hi', 'very bad', 'good']
Instead of looping through the dictionary loop through the message and then you can look for word matches when you hit a letter that matches the start of a key, like so:而不是遍历字典循环遍历消息,然后您可以在点击与键开头匹配的字母时查找单词匹配,如下所示:
item_dict = {
"okay": ("Mythical", "50000"),
"hello": ("Mythical", "17500"),
"hi": ("Legendary", "14500"),
"good": ("Legendary", "11600"),
"very bad": ("Common", "1"),
}
msg = input("Enter ")
new_list = []
for index, letter in enumerate(msg):
for key in item_dict.keys():
if letter == key[0]:
if msg[index:index+len(key)] == key:
new_list.append(key)
break
print(new_list)
This solution can also handle spaces in the dictionary keys, albeit at a higher computation cost.该解决方案还可以处理字典键中的空格,尽管计算成本更高。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.