在Python中将文件拆分为字典

2024-09-19 20:51:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我只是一个初级python用户,如果这是一个非常简单的问题,我深表歉意。我有一个包含两个列表的文件,列表被一个标签分开。我想将其存储在字典中,以便每个条目都与选项卡后面的相应条目相关联,这样:

cat hat
mouse bowl
rat nose
monkey uniform
dog whiskers
elephant dance

将被分为

{'cat'; 'hat', 'mouse' ; 'bowl') etc. etc. 

名单很长。你知道吗

这就是我所尝试的:

enhancerTAD = open('TAD_to_enhancer.map', 'r')
list = enhancerTAD.split()

for entry in list:
    key, val = entry.split('\t')
    ET[key] = val

print ET

这是我最近的一次尝试,下面是我收到的错误消息:

enhancerTAD = open('TAD_to_enhancer.map', 'r').read()
ET = {}
lst = enhancerTAD.split("\n")
for entry in lst:
  key, val = entry.strip().split(' ',1)
  ET[key] = val

enhancergene = open('enhancer_to_gene_map.txt', 'r').read()
GE = {}
lst1 = enhancergene.split("\n")
for entry in lst1:
  key, val = entry.strip().split(' ',1)
  GE[key] = val

geneTAD = open('TAD_to_gene_map.txt', 'r').read()
GT = {}
lst2 = geneTAD.split("\n")
for entry in lst2:
  key, val = entry.strip().split(' ',1)
  GT[key] = val

“文件”增强子tamaybe.py,第13行,在 键,val=入口.strip().拆分(“”,1) ValueError:需要多个值才能解包


Tags: tokeyinmapforreadvalopen
2条回答

您可以尝试:

with open('foo.txt', 'r') as f:
    print dict(line.strip().split('\t', 1) for line in f)

结果:

{'monkey': 'uniform', 'dog': 'whiskers', 'cat': 'hat', 'rat': 'nose', 'elephant': 'dance', 'mouse': 'bowl'}

对原始方法的修改:

enhancerTAD = open('TAD_to_enhancer.map', 'r').read()
ET={}
lst = enhancerTAD.split("\n")
for entry in lst:
   key, val = entry.strip().split('\t',1)
   ET[key] = val
print ET

积分:

1.您的原始方法失败,因为您试图在文件对象而不是文件内容上拆分

即)

a=open("amazon1.txt","r")
c=a.split()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'file' object has no attribute 'split'

2.您必须读取文件的内容才能拆分它

即:

enhancerTAD =open("amazon1.txt","r").read()

3.由于在每行中都有键、值对,因此必须在新行处进行初始拆分

4.然后您可以遍历列表,并在\t处再次拆分它并形成字典

Juniorcomposer方法执行所有这两行代码,而且更具python风格

相关问题 更多 >