【问题标题】:Splitting text in tab delimited format in python, adding it to list and writing it to a file... is there a better way?在python中以制表符分隔格式拆分文本,将其添加到列表并将其写入文件......有更好的方法吗?
【发布时间】:2015-12-03 09:11:15
【问题描述】:

我是 python 脚本的新手。我正在从制表符分隔的vcf 文件中提取数据。我的脚本有效,但我尝试使用 word[0:2] 将字符串连接到一个列表中,但这不起作用,所以我通过手动拆分来添加数据:

即:word[0] + "\t" + word[1] + "\t" + word[2]

我不知道为什么我必须这样做,因为当我使用lst = word[0:2] 命令返回“只能将列表(而不是“str”)连接到列表。这是为什么?

我的整个代码是:

lst = []
for line in my_file:
    if 'chr' in line:   
        word = line.split("\t")
        adp = word[7].split(";")
        pc = word[9].split(":")
        s = adp[0].split("=")
        lst = word[0] + "\t" + word[1] + "\t" + word[3] + "\t" + word[4] + "\t" + s[1] + "\t" + pc[6] + "\n"
        outputfile.write(lst)

我怎样才能使它更简洁?

谢谢

【问题讨论】:

  • pypi.python.org/pypi/PyVCF 是一个用于解析变体调用格式文件的 python 模块 --- 我不知道这是否是您想要的,或者您的 DIBY 方法是否更好。

标签: python string list split


【解决方案1】:

连接字符串时使用join

lst = []
for line in my_file:
    if 'chr' in line:   
        word = line.split("\t")
        lst.extend(word[7].split(";"))
        lst.extend(word[9].split(":"))
        lst.extend(adp[0].split("="))
        out = '\t'.join(lst)
        outputfile.write(out)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-22
    • 1970-01-01
    • 2018-10-20
    • 1970-01-01
    • 2018-07-14
    • 2013-07-05
    • 2016-08-10
    • 2016-01-02
    相关资源
    最近更新 更多