如何检查字符串中的多个特定单词?

时间:2019-06-06 02:44:55

标签: python-2.7

我正在开发一个基于文本的游戏,并且希望该程序按用户的答案顺序搜索多个特定的单词。例如,如果不使用户键入“ Take item”,我就不会在用户的响应中找到单词“ Take”和“ item”。

我知道您可以使用

    if this in that

检查该单词是否在该字符串中,但是多个单词之间有绒毛呢?

我现在使用的代码是

if ("word1" and "word2" and "word3) in ans:

但这很长,并且不适用于基于文本的游戏中的每个输入。还有什么办法?

2 个答案:

答案 0 :(得分:1)

基于正则表达式的解决方案可能是使用re.match

input = "word1 and word2 and word3"
match = re.match(r'(?=.*\bword1\b)(?=.*\bword2\b)(?=.*\bword3\b).*', input)
if match:
    print("MATCH")

使用的正则表达式模式使用肯定的外观,断言每个单词都出现在字符串中。

答案 1 :(得分:0)

如果我正确理解了问题,我们可能想在这里设计一个包含键和值的库,然后查找所需的输出:

word_action_library={
   'Word1':'Take item for WORD1',
   'Some other words we wish before Word1':'Do not take item for WORD1',
   'Before that some WOrd1 and then some other words':'Take items or do not take item, if you wish for WORD1',

   'Word2':'Take item for WORD2',
   'Some other words we wish before Word2':'Do not take item for WORD2',
   'Before that some WOrd2 and then some other words':'Take items or do not take item, if you wish for WORD2',

   }

print list(value for key,value in word_action_library.iteritems() if 'word1' in key.lower())
print list(value for key,value in word_action_library.iteritems() if 'word2' in key.lower())

输出

['Take items or do not take item, if you wish for WORD1', 'Do not take item for WORD1', 'Take item for WORD1']
['Take items or do not take item, if you wish for WORD2', 'Do not take item for WORD2', 'Take item for WORD2']
相关问题