首页 文章

在Python中将文件拆分为字典

提问于
浏览
1

我只是一个初学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

文件“enhancertadmaybe.py”,第13行,在key中,val = entry.strip() . split('',1)ValueError:需要多于1个值才能解压缩

2 回答

  • 0

    修改原始方法:

    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
    

    Points:

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

    i.e)

    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.您必须阅读文件的内容才能将其拆分

    i.e.)

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

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

    然后,您可以遍历列表并再次将其拆分为 \t 并形成字典

    Juniorcomposer 方法完成所有这两行代码并且更加pythonic

  • 5

    你可以试试:

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

相关问题