如何从Python中读取Perl数据结构? [英] How can I read Perl data structures from 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'
);
使用纯Python将这些文件的内容转换为Python等效的数据结构?暂时我们可以假设没有真正的表达式来评估,只有结构化数据。
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.
推荐答案
情况是。这里是我的假设:你将做一次从Perl到Python的转换。
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有这个
%config = (
'color' => 'red',
'numbers' => [5, 8],
qr/^spam/ => 'eggs'
);
在Python中,它将是
In Python, it would be
config = {
'color' : 'red',
'numbers' : [5, 8],
re.compile( "^spam" ) : 'eggs'
}
所以,我猜这是一堆RE替换
So, I'm guessing it's a bunch of RE's to replace
-
%variable =(
withvariable = {
-
); 与
}
/ li>
variable => value
withvariable:value
qr /.../ = ;
与re.compile(r...):value
%variable = (
withvariable = {
);
with}
variable => value
withvariable : value
qr/.../ =>
withre.compile( r"..." ) : value
但是,Python的内置 dict
不会使用regex作为散列键做任何异常。为此,您必须编写自己的 dict
子类,并覆盖 __ getitem __
以单独检查REGEX键。
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, ) )
这里是使用类似Perl的dict的例子。
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屋!