python正则表达读取word_Python中使用正则表达式作为键的字典

解决方案

这里没有魔法,所以必须对每一对进行迭代: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'))

# []

如果输出顺序很重要,则必须使用^{}

注意Explicit is better than implicit.

如果你想用Python实现某件事,通常必须编写它。语法可能简短明了,但仍然需要明确地写出来。在

所以不,字符串不会被认为与dict中匹配的regex具有相同的哈希

如果你在寻找更多的魔力,你可以看看Ruby。它对patterns有更广泛的定义,可以是类、正则表达式或字符串:

^{pr2}$

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值