python调用perl,如何从Python中读取Perl数据结构?

I've often seen people use Perl data structures in lieu of configuration files; i.e. a lone file containing only:

%config = (

'color' => 'red',

'numbers' => [5, 8],

qr/^spam/ => 'eggs'

);

What's the best way to convert the contents of these files into Python-equivalent data structures, using pure Python? For the time being we can assume that there are no real expressions to evaluate, only structured data.

解决方案

Not sure what the use case is. Here's my assumption: you're going to do a one-time conversion from Perl to Python.

Perl has this

%config = (

'color' => 'red',

'numbers' => [5, 8],

qr/^spam/ => 'eggs'

);

In Python, it would be

config = {

'color' : 'red',

'numbers' : [5, 8],

re.compile( "^spam" ) : 'eggs'

}

So, I'm guessing it's a bunch of RE's to replace

%variable = ( with variable = {

); with }

variable => value with variable : value

qr/.../ => with re.compile( r"..." ) : value

However, Python's built-in dict doesn't do anything unusual with a regex as a hash key. For that, you'd have to write your own subclass of dict, and override __getitem__ to check REGEX keys separately.

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, ) )

Here's the example of using a Perl-like dict.

>>> pat= re.compile( "hi" )

>>> a = { pat : 'eggs' } # native dict, no features.

>>> x=PerlLikeDict( a )

>>> x['b']= 'c'

>>> x

{<_sre.sre_pattern object at>: 'eggs', 'b': 'c'}

>>> x['b']

'c'

>>> x['ji']

Traceback (most recent call last):

File "", line 1, in

File "", line 10, in __getitem__

KeyError: "key 'ji' not found"

>>> x['hi']

'eggs'

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值