文件到dict [英] File to dict

查看:43
本文介绍了文件到dict的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,


我写了这个小实用程序函数,用于将传统的

文件转换为Python dict:

def lookupdmo(domain):

lines = open(''/ etc / virtual / domainowners'',''r'')。readlines()

lines = [[ y.lstrip()。rstrip()for x in x.split('':'')] for x in

lines]

lines = [x for x在行中,如果len(x)== 2]

d = dict()

行中的行:

d [line [0]] = line [1]

return d [domain]


/ etc / virtual / domainowners文件包含双冒号分隔

条目:

domain1.tld:owner1

domain2.tld:own2

domain3.another:某人

....


现在,上面的lookupdmo函数有效。但是,用这种方式将文件转换为dicts是相当繁琐的,而且我有很多这样的转换文件(比如自定义''passwd'''虚拟电子邮件的文件

帐户等。


是否有更聪明/更pythonic的方式解析文件,如

这个?说,我想将包含以下条目的文件转换为列表,其中doublecolon被视为

分隔符,即:


tm:$ 1 $ aaaa $ bbbb:1010:6 :: / home / owner1 / imap / domain1.tld / tm:/ sbin / nologin


会得到变成了这个:


[[''tm'',''$ 1 $ aaaa $ bbbb'',''1010'',''6'',''/ home / owner1 / imap / domain1.tld /

tm'',''/ sbin / nologin''] [...] [...]]

Hello everyone,

I have written this small utility function for transforming legacy
file to Python dict:
def lookupdmo(domain):
lines = open(''/etc/virtual/domainowners'',''r'').readlines()
lines = [ [y.lstrip().rstrip() for y in x.split('':'')] for x in
lines]
lines = [ x for x in lines if len(x) == 2 ]
d = dict()
for line in lines:
d[line[0]]=line[1]
return d[domain]

The /etc/virtual/domainowners file contains double-colon separated
entries:
domain1.tld: owner1
domain2.tld: own2
domain3.another: somebody
....

Now, the above lookupdmo function works. However, it''s rather tedious
to transform files into dicts this way and I have quite a lot of such
files to transform (like custom ''passwd'' files for virtual email
accounts etc).

Is there any more clever / more pythonic way of parsing files like
this? Say, I would like to transform a file containing entries like
the following into a list of lists with doublecolon treated as
separators, i.e. this:

tm:$1$aaaa$bbbb:1010:6::/home/owner1/imap/domain1.tld/tm:/sbin/nologin

would get transformed into this:

[ [''tm'', ''$1$aaaa$bbbb'', ''1010'', ''6'', , ''/home/owner1/imap/domain1.tld/
tm'', ''/sbin/nologin''] [...] [...] ]

推荐答案

1


aaaa


bbbb:1010:6 :: / home /owner1/imap/domain1.tld/tm:/sbin/nologin

会变成这样:


[[''tm '',''
bbbb:1010:6::/home/owner1/imap/domain1.tld/tm:/sbin/nologin

would get transformed into this:

[ [''tm'', ''


这篇关于文件到dict的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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