2

我有这个文本文件

application/andrew-inset                        ez
application/applixware                          aw
application/atom+xml                            atom
application/atomcat+xml                         atomcat
application/atomsvc+xml                         atomsvc
application/ccxml+xml                           ccxml
application/cdmi-capability                     cdmia
application/cdmi-container                      cdmic
image/jpeg                                      jpeg jpg jpe

我想转换成键值对的python字典。我怎样才能做到这一点。

如果有多个值,我也很困惑我应该怎么做。

我想从 mimetypes 中获取文件扩展名

所以基本上在多重价值的情况下我想得到第一个。

例如

mydict['image/jpeg']应该返回jpeg

这就是我所追求的

import shlex
f = open("mimetypes.txt","r")
mydict = dict()
for line in f:
        k,v = shlex.split(line.strip())
        mydict[k.strip()] =  v.strip()

f.close()
f2 = open("mimetest.txt","w")
f2.write(mydict)
f2.close()

我明白了

Traceback (most recent call last):
  File "makedict.py", line 5, in <module>
    k,v = shlex.split(line.strip())
ValueError: too many values to unpack
4

2 回答 2

3

编辑:根据您的更新,您非常接近 - 问题是因为这一行:

k,v = shlex.split(line.strip())

如您所知,它适用于具有两个项目的任何元素,但是当您拥有多个项目时问题就来了。例如:

In [1]: import shlex

In [2]: line = 'one two'

In [3]: k,v = shlex.split(line.strip())

In [4]: print k, v
one two

In [5]: line = 'one two three'

In [6]: k,v = shlex.split(line.strip())
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)

/<ipython console> in <module>()

ValueError: too many values to unpack

发生的事情是您试图使用包含三个项目的列表来分配两个变量,这会给您带来该错误。您可以在代码中做的一件事是通过执行以下操作将返回的列表限制为仅返回两项:

In [7]: line = 'one two three'

In [8]: k,v = shlex.split(line.strip())[:2]

In [9]: print k, v
one two

一般的想法是你创建一个字典,打开文件,然后在每一行,去掉尾随的换行符,在空格上分割并取结果列表的前两个元素:

In [5]: d = {}

In [6]: with open('mime.txt', 'rb') as f:
   ...:     for line in f:
   ...:         mime, val = line.strip().split()[:2]
   ...:         d[mime] = val
   ...:         
   ...:         

In [7]: d
Out[7]: 
{'application/andrew-inset': 'ez',
 'application/applixware': 'aw',
 'application/atom+xml': 'atom',
 'application/atomcat+xml': 'atomcat',
 'application/atomsvc+xml': 'atomsvc',
 'application/ccxml+xml': 'ccxml',
 'application/cdmi-capability': 'cdmia',
 'application/cdmi-container': 'cdmic',
 'image/jpeg': 'jpeg'}

In [8]: d['image/jpeg']
Out[8]: 'jpeg'

如果您需要存储所有项目,您可以这样做:

In [1]: d = {}

In [2]: with open('mime.txt', 'rb') as f:
   ...:     for line in f:
   ...:         line = line.strip().split()
   ...:         d[line[0]] = line[1:]
   ...:         
   ...:         

In [3]: d
Out[3]: 
{'application/andrew-inset': ['ez'],
 'application/applixware': ['aw'],
 'application/atom+xml': ['atom'],
 'application/atomcat+xml': ['atomcat'],
 'application/atomsvc+xml': ['atomsvc'],
 'application/ccxml+xml': ['ccxml'],
 'application/cdmi-capability': ['cdmia'],
 'application/cdmi-container': ['cdmic'],
 'image/jpeg': ['jpeg', 'jpg', 'jpe']}

这包括所有的 MIME 类型,所以如果你只想要第一个,你可以调用给定类型值的第一个元素:

In [4]: d['image/jpeg'][0]
Out[4]: 'jpeg
于 2012-12-31T03:31:17.550 回答
0

另一种方法是:

dic = {}
file =  open("filename","r")
contents = file.readlines()
for content in contents:
    value = filter(lambda a: a !='',content.split(" "))
    dic[value[0]] = value[1]
file.close()
print dic['image/jpeg']

我们用“”分割每一行,然后删除列表中的任何“”。然后我们为字典分配值。

于 2012-12-31T03:44:47.707 回答