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

时间:2015-01-23 00:45:17

标签: python regex string list match

我正在尝试制作文字冒险游戏,而我当前的方法涉及具有有效命令的列表/数组:

#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']

我想做的是能够在输入命令时匹配其中两个字符串,与此类似(但显然有效):

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

我已尝试过正则表达式,但似乎无法使它们正常工作,因为我不确定第二个参数需要的是什么:

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

如果有人可以就如何继续提供一些指导或建议,我们将不胜感激。

2 个答案:

答案 0 :(得分:1)

你需要拆分空格(command.split()而不用参数这样做),然后得到两个命令。然后你可以检查:

if firstWord in act_verb and secondWord in thing_noun

答案 1 :(得分:0)

如果您的令牌没有空格,那将会更容易,例如'pick_up''go_to'。然后你可以这样分割输入:

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