如何从 Python 读取 Perl 数据结构? [英] How can I read Perl data structures from Python?

查看:32
本文介绍了如何从 Python 读取 Perl 数据结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常看到人们使用 Perl 数据结构代替配置文件;即一个单独的文件只包含:

%config = ('颜色' =>'红色的','数字' =>[5, 8],qr/^垃圾邮件/=>'蛋');

使用纯 Python 将这些文件的内容转换为 Python 等效数据结构的最佳方法是什么?暂时我们可以假设没有要评估的真正表达式,只有结构化数据.

解决方案

不确定用例是什么.这是我的假设:您将进行一次从 Perl 到 Python 的一次性转换.

Perl 有这个

%config = ('颜色' =>'红色的','数字' =>[5, 8],qr/^垃圾邮件/=>'蛋');

在 Python 中,它会是

config = {'红色','数字' : [5, 8],重新编译(^垃圾邮件"):'鸡蛋'}

所以,我猜是一堆 RE 来代替

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

然而,Python 的内置 dict 并没有用正则表达式作为散列键做任何不寻常的事情.为此,您必须编写自己的 dict 子类,并覆盖 __getitem__ 以单独检查 REGEX 键.

class PerlLikeDict( dict ):模式类型=类型(重新编译("))def __getitem__( self, key ):如果键入 self:return super( PerlLikeDict, self ).__getitem__( key )对于 k 自身:如果 type(k) == self.pattern_type:如果 k.match(key):回归自我[k]引发 KeyError( "key %r not found" % ( key, ) )

这是使用类似 Perl 的 dict 的示例.

<预><代码>>>>pat= re.compile( "hi" )>>>a = { pat : 'eggs' } # 原生字典,没有特征.>>>x=PerlLikeDict( a )>>>x['b'] = 'c'>>>X{<_sre.SRE_Pattern 对象在 0x75250>: 'eggs', 'b': 'c'}>>>x['b']'C'>>>x['ji']回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中文件",第 10 行,在 __getitem__ 中KeyError:找不到关键'ji'">>>x['嗨']'蛋'

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 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'

这篇关于如何从 Python 读取 Perl 数据结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆