Min*_*iMe 0 python regex dictionary
import re
collections ={}
collections [re.compile ('n.*')]='word that starts with n'
Run Code Online (Sandbox Code Playgroud)
我希望集合 ['never'] 返回“以 n 开头的单词”,但上述情况不会发生。
我做错了什么?
这里没有魔法发生,所以你必须迭代每一对:
import re
collections = {}
collections[re.compile('n.*')] = 'word that starts with n'
collections[re.compile(r'\b....\b')] = '4 letter word'
def find_matching_regexen(word, dicts=collections):
return [description for regex, description in dicts.items() if regex.match(word)]
print(find_matching_regexen('never'))
# ['word that starts with n']
print(find_matching_regexen('boat'))
# ['4 letter word']
print(find_matching_regexen('nice'))
# ['word that starts with n', '4 letter word']
print(find_matching_regexen('dog'))
# []
Run Code Online (Sandbox Code Playgroud)
如果输出顺序很重要,则必须使用 OrderedDict
显式优于隐式。
如果你想用 Python 实现一些东西,你通常必须编写它。语法可能简短明了,但仍然需要明确地编写。
所以不,字符串不会被视为与字典中的匹配正则表达式具有相同的哈希值。
如果你正在寻找更多的魔法,你可以看看 Ruby。它有更广泛的模式定义,可以是类、正则表达式或字符串:
[1, "abc", 2, "def"].grep(/a/)
# => ["abc"]
[1, "abc", 2, "def"].grep(Integer)
# => [1, 2]
Run Code Online (Sandbox Code Playgroud)
模式也用于 case 语句。例如,您可以在不进行转换或显式方法调用的情况下将字符串与正则表达式匹配:
def find_matching_regexen(word)
case word
when /^n.*/
"Word that starts with n"
when /\b....\b/
"4 letter word"
end
end
puts find_matching_regexen("boat")
# "4 letter word"
puts find_matching_regexen("nice")
# "Word that starts with n"
puts find_matching_regexen("dog")
# nil
Run Code Online (Sandbox Code Playgroud)