0

假设我有以下字典:

d = {"word1":0, "word2":0}

对于这个正则表达式,我需要验证字符串中的单词不是该字典中的键。

出于正则表达式的目的,是否可以将变量设置为字典中没有的任何内容?

4

2 回答 2

2

在这种情况下忘记正则表达式:

 test = "word1 word2 word3"     # your string
 words = test.split(' ')        # words in your string
 dict = {"word1":0, "word2":0}  # your dict     
 for word in words:
     if word in dict:
         print word, "is a key in dict"
     else:
         print word, "isn't a key in dict"
于 2013-05-08T09:12:59.193 回答
1
>>> d = {"foo":0, "spam":0}
>>> test = "This is a string with many words, including foo and bar"
>>> any(word in d for word in test.split())
True

如果标点符号是一个问题(例如,用这种方法"This is foo."找不到foo),并且因为你说你所有的词都是字母数字,你也可以使用

>>> import re
>>> test = "This is foo."
>>> any(word in d for word in re.findall("[A-Za-z0-9]+", test))
于 2013-05-08T09:19:11.293 回答