0

我有一个巨大的文本文件,其中包含这样的数据集

EOG61ZHH8   ENSRNOG00000004762  627
EOG61ZHH8   ENSRNOG00000004762  627
EOG61ZHH9   ENSG00000249709 1075
EOG61ZHH9   ENSG00000249709 230
EOG61ZHH9   ENSG00000249709 87
EOG61ZHHB   ENSG00000134030 2347
EOG61ZHHB   ENSG00000134030 3658
EOG61ZHHB   ENSRNOG00000018342  241
EOG61ZHHB   ENSRNOG00000018342  241
EOG61ZHHC   ENSBTAG00000006084  1159
EOG61ZHHC   ENSG00000158828 820
EOG61ZHHC   ENSMMUG00000000126  631

我想像这样转换或拆分它

EOG61ZHH8.txt
ENSRNOG00000004762  627
ENSRNOG00000004762  627
EOG61ZHH9.txt
ENSG00000249709 1075
ENSG00000249709 230
ENSG00000249709 87

等等。我不知道从哪里开始从上面的文本文件中获取新的 txt 文件,我之前做过这件事,但是条目在条目开始之前有 '[' 符号,现在我有很多文件但没有任何特殊符号来转换它们这个是我在 python 中完成的代码

with open("entry.txt") as f: 
  for line in f:
    if line[0] == "[":
     if out: out.close()
     out = open(line.split()[1] + ".txt", "w")
   else: out.write(line)'

我在windows中使用它,所以我知道linux awk命令,所以不需要关于linux的信息

4

2 回答 2

1

You need only a few adjustments to your script:

out = None
oldfile = None
with open("entry.txt") as f: 
    for line in f:
        newfile = l.split("\t")[0]
        if newfile != oldfile:
            if out: out.close()
            out = open(newfile + ".txt", "w")
            oldfile = newfile
        out.write("\t".join(line.split("\t")[1:]))
于 2013-03-21T21:47:33.353 回答
0

使用正则表达式;

import re

string = '    EOG61ZHH8   ENSRNOG00000004762  627    EOG61ZHH8   ENSRNOG00000004762  627    EOG61ZHH9   ENSG00000249709 1075    EOG61ZHH9   ENSG00000249709 230    EOG61ZHH9   ENSG00000249709 87    EOG61ZHHB   ENSG00000134030 2347    EOG61ZHHB   ENSG00000134030 3658    EOG61ZHHB   ENSRNOG00000018342  241    EOG61ZHHB   ENSRNOG00000018342  241    EOG61ZHHC   ENSBTAG00000006084  1159    EOG61ZHHC   ENSG00000158828 820    EOG61ZHHC   ENSMMUG00000000126  631'

result = re.findall('\s+(.*?)\s+(.*?)\s+(\d+)', string, re.S)

buffer = {}

for i in result:
    if not i[0] in buffer:
        buffer[i[0]] = ''

    buffer[i[0]] = buffer[i[0]] + i[1] + '  ' + i[2] + '\n'

for i in buffer.iteritems():
    print i

    filename = i[0] + '.txt'
    content = i[1] # you could remove the unneeded "\n" here with substring if wanted

    # CODE: Create the file with "filename"

    # CODE: Write "content" to the file
于 2013-03-21T22:01:19.880 回答