简体   繁体   English

python:将dna序列文本文件读取到字典

[英]python: read dna sequence text file to dictionary

I'm trying to convert a text file containing DNA sequences to a dictionary in python. 我正在尝试将包含DNA序列的文本文件转换为python中的字典。 The file is setup in columns. 该文件在列中设置。

TTT F
TCT S
TAT Y
TGT C
TTC F


import os.path

if os.path.isfile("GeneticCode_2.txt"):
    f = open('GeneticCode_2.txt', 'r')
    my_dict = eval(f.read())

Trying to get it to: 试图使它达到:

my_dict = {TTT: F, TCT: S, TAT: Y} 

You can use the dict constructor using an iterable of pairs (2-tuples) and pass it the split lines of your file: 您可以使用dict构造函数,使用成对的迭代器(2元组),并将文件的分割行传递给它:

with open('GeneticCode_2.txt', 'r') as f:
    my_dict = dict(line.split() for line in f)  
    # works only if file only contains lines that split into exactly 2 tokens
d = {}
with open("GeneticCode_2.txt") as infile:
    for line in infile:
        k,v = line.strip().split()
        d[k] = v

This isn't the most compact way of doing it, but it is very readable. 这不是最紧凑的方法,但是它非常易读。

my_dict = dict()

for line in f.readlines():
    parts = line.strip().split()
    if not len(parts) < 2:
        my_dict[parts[0]] = parts[1]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM