简体   繁体   English

如何将字符串与列表/数组中的元素匹配-Python

[英]How to match a string to an element in a list/array - python

I'm trying to make a text adventure game, and my current approach involves lists/arrays that have valid commands: 我正在尝试制作文本冒险游戏,而我目前的方法涉及具有有效命令的列表/数组:

#action verbs
act_verb = ['take', 'pick up', 'remove', 'shift', 'position', 'reposition', 'lift', 'kick', 'move']
#fight verbs
fight_verb = ['hit', 'kill', 'wack', 'dismember', 'destroy', 'obliterate']
#movement verbs
mov_verb = ['move', 'crawl', 'go', 'travel', 'walk', 'slither', 'go to', 'go to the', 'run']
#just-in-case adjectives
jic_adj = ['adjective']
#room nouns (ie directions, doors)
room_noun = ['north', 'n', 'south', 's', 'west', 'w', 'east', 'e', 'up', 'u', 'down', 'd']
#thing/object nouns
thing_noun = ['sword', 'troll', 'rug', 'door']

What I would like to do is be able to match two of those strings when a command is input, in a vein similar to this (but working, obviously): 我想做的是能够在输入命令时匹配其中的两个字符串,其操作与此类似(但是很明显):

command = raw_input('>')
if command == act_verb + thing_noun
    print "output"

I've tried regular expressions, but can't seem to make them work, as I am not sure what the second argument required would be: 我已经尝试过正则表达式,但似乎无法使它们起作用,因为我不确定所需的第二个参数是什么:

matchaverb = re.match(act_verb, )
matchtnoun = re.match(thing_noun, )

If anyone could provide some guidance or advice on how to continue, it would be greatly appreciated. 如果有人可以提供一些有关如何继续的指导或意见,将不胜感激。

You would need to split on whitespace ( command.split() without an argument does this) and then get the two commands. 您将需要在空格上分割command.split()不带参数的command.split()执行此操作),然后获取两个命令。 Then you can check: 然后您可以检查:

if firstWord in act_verb and secondWord in thing_noun

It would be easier if your tokens would be without spaces, eg 'pick_up' , 'go_to' . 如果您的令牌没有空格(例如'pick_up''go_to' 'pick_up'会更容易。 Then you can split the input this way: 然后,您可以按以下方式拆分输入:

tokens = command.split()
# get actions from command tokens:
actions = set(act_verbs) & set(tokens)
# process actions
if 'take' in actions:
   ....

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

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