栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何从Python读取Perl数据结构?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何从Python读取Perl数据结构?

不知道用例是什么。这是我的假设:您将要进行一次从Perl到Python的转换。

Perl有这个

%config = (    'color' => 'red',    'numbers' => [5, 8],    qr/^spam/ => 'eggs');

在Python中,

config = {    'color' : 'red',    'numbers' : [5, 8],    re.compile( "^spam" ) : 'eggs'}

所以,我想这是一堆可替换的RE

  • %variable = (
    variable = {
  • );
    }
  • variable => value
    variable : value
  • qr/.../ =>
    re.compile( r"..." ) : value

但是,

dict
使用正则表达式作为哈希键,Python的内置功能不会做任何异常。为此,您必须编写自己的的子类
dict
,并进行重写
__getitem__
以分别检查REGEX键。

class PerlLikeDict( dict ):    pattern_type= type(re.compile(""))    def __getitem__( self, key ):        if key in self: return super( PerlLikeDict, self ).__getitem__( key )        for k in self: if type(k) == self.pattern_type:     if k.match(key):         return self[k]        raise KeyError( "key %r not found" % ( key, ) )

这是使用类似Perl的字典的示例。

>>> pat= re.compile( "hi" )>>> a = { pat : 'eggs' } # native dict, no features.>>> x=PerlLikeDict( a )>>> x['b']= 'c'>>> x{<_sre.SRE_Pattern object at 0x75250>: 'eggs', 'b': 'c'}>>> x['b']'c'>>> x['ji']Traceback (most recent call last):  File "<stdin>", line 1, in <module>  File "<stdin>", line 10, in __getitem__KeyError: "key 'ji' not found">>> x['hi']'eggs'


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/640412.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号