替换元素以重新格式化数据集

用户名

我正在尝试解析基因型数据,本质上是将其转换为其他软件使用,如果问题过于具体,抱歉,但是任何评论和建议都将不胜感激。

ID, exp, control
1, aa, bb
2, ab, aa
3, ab, -

我会这样转换:

  1. 重复每一列,但重复第一列。
  2. 替换'aa''bb'因为'a''b'当它是'ab'作为第一个将被替换'a',重复的将被替换为'b'

例如

    ID exp exp control control
    1 a a b b
    2 a b a a
    3 a b 0 0

我以某种方式设法实现了第一个目标,但是我发现打印输出有点奇怪,并且所有替换都没有执行:

ID exp   exp     control
     control

1 aa     aa  bb
     bb

2 ab     ab  aa
     aa

3 ab     ab  -
     -       

这是我的代码:

#!/usr/bin/env python

inputfile = open("test.txt", 'r')
outputfile = open("solomon.txt", 'w')
matchlines = inputfile.readlines()

for line in matchlines: 
        line_parts = line.strip() #strip the end space
        line_parts = line.split(',') #split the line
        output_parts = []
        for part in line_parts[1:]:  #start from 2nd element, so 1st column not duplicate

            if part == 'aa':
               part = part.replace('aa', 'a')
            elif part == 'bb':
               part = part.replace('bb', 'b')
            elif part == '-':
               part = part.replace('-', '0')
            elif part == 'ab':
                 '''the original one will be replaced with 'a' the duplciatd on will be replaced as 'b' '''
            else:
                 print 'Nothing is matched'
            output_part = part + '\t' + part #duplicate each element (1st goal)             
            output_parts.append(output_part) #populate the line      
            line = '\t'.join(output_parts)   #join elements in the line with a tab                
        outputfile.write(line_parts[0] + line + "\n")

inputfile.close()
outputfile.close()
琼斯·哈珀

我建议为此使用一个单独的功能,从而使其更容易与其他元素分开进行开发和测试。

def process_line(line_parts):
    out = line_parts[:1]
    for part in line_parts[1:]:
        if part == "-":
            out.extend('00')
        else:
            out.extend(part)
    return out

这给出了,例如

>>> process_line(['1', 'aa', '-'])
['1', 'a', 'a', '0', '0']

>>> process_line(['1', 'ab', 'bb'])
['1', 'a', 'b', 'b', 'b']

您可以使用以下命令轻松地将其用空格分隔str.join

>>> " ".join(['1', 'a', 'a', '0', '0'])
'1 a a 0 0'

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章