2024-10-01 00:32:11 发布
网友
我想做个审查员。而不是
if curseword in typed or curseword2 in typed or curseword3 typed: print "No cursing! It's not nice!"
我想这样做,我可以有一个列表中的所有单词,并可以检查这些单词是否在列表中。注意:如果使用while循环的“if any…”代码,它有太多的输出要处理。你知道吗
可以使用any和生成器:
any
cursewords = ['javascript', 'php', 'windows'] if any(curseword in input for curseword in cursewords): print 'onoes'
或者,为了更灵活一点,可以使用regex(如果您还想检测大写诅咒词):
if re.search(r'javascript|php|windows', input, re.IGNORECASE): print 'onoes'
(如果您不熟悉regex,the Python docs have got a nice tutorial)
如果您只想忽略case而不想弄乱regexen,您也可以这样做:
# make sure these are all lowercase cursewords = ['javascript', 'php', 'windows'] input_lower = input.lower() if any(curseword in input_lower for curseword in cursewords): print 'onoes'
使用、过滤内置方法:
>>>test = ['ONE', 'TWO', 'THREE', 'FOUR'] >>>input = 'TWO' >>> if filter(lambda s: s in input, test): print 'OK' OK >>> input = 'FIVE' >>> >>> if filter(lambda s: s in input, test): print 'OK' >>> #nothing printed
对输入使用for循环,检查每个单词是否在cursewords列表中。你知道吗
cursewordList = ['a','b' ...] for word in input: if word in cursewordList: print "No cursing! It's not nice!"
可以使用
any
和生成器:或者,为了更灵活一点,可以使用regex(如果您还想检测大写诅咒词):
(如果您不熟悉regex,the Python docs have got a nice tutorial)
如果您只想忽略case而不想弄乱regexen,您也可以这样做:
使用、过滤内置方法:
对输入使用for循环,检查每个单词是否在cursewords列表中。你知道吗
相关问题 更多 >
编程相关推荐