字典与正则表达式作为Python中的键

时间:2017-03-22 15:26:36

标签: python regex dictionary

import re
collections ={}
collections [re.compile ('n.*')]='word that starts with n'

我希望集合['never']返回'以n开头的单词' 但上述情况并未发生。

我做错了什么?

2 个答案:

答案 0 :(得分:4)

解决方案

这里没有任何魔法,所以你必须迭代每一对:

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

如果输出顺序很重要,则必须使用OrderedDict

注意

来自zen of python

  

明确比隐含更好。

如果你想在Python中实现某些东西,你通常必须编写它。语法可能简短明了,但仍需要明确写出。

所以不,字符串不会被视为与dict中匹配的正则表达式具有相同的哈希值。

如果你正在寻找更多魔法,你可以看看Ruby。它有一个更广泛的patterns定义,可以是类,regexen或字符串:

[1, "abc", 2, "def"].grep(/a/)
# => ["abc"]
[1, "abc", 2, "def"].grep(Integer)
# => [1, 2]

模式也用于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

答案 1 :(得分:-1)

def collections(text):
  if re.compile('n.*').findall(text):
    return 'word that starts with n'
print collections('never')
>>> word that starts with n
相关问题