更改下一循环的输入字符串

时间:2016-11-01 13:19:29

标签: python string loops

我一直在寻找一种方法来做一天但却无法找到我真正需要的东西。我有2个文件。 FIRST文件在第二列中的一列中位置为NAMES,在第三列中为LETTERS。在SECOND文件中,我在第一列中有NAMES,在第二列中有STRINGS。我有一个循环遍历FIRST文件中的每一行,将NAMES与每行的SECOND文件相匹配,然后转到POSITIONS并使用LETTERS更改STRING。循环工作完美,但我无法保留下一封信的更改。

就像

第一个文件

NAME1   2   X
NAME1   5   Z
NAME1   7   J
NAME2   3   P
NAME2   6   D

第二个文件

NAME1   AAAAAAAAA
NAME2   BBBBBBB

我使用STRING作为输入并在循环期间使用更改的LETTER创建NEWSTRING,当我在循环中打印它时,我得到第一个循环:

AXAAAAAAA

在第二次之后:

AAAAZAAAA

我正在寻找的是一种神奇的单线,让它在循环内部进行,类似于STRING = NEWSTRING,以便我在下一个循环中的输入将是NEWSTRING

AXAAAAAAA

因此会生成

AXAAZAAAA

在第二个循环中

我尝试过添加,添加,列表和其他一些内容,但都没有效果。

with open ("FILE1.txt")as f:  
        POS=f.readlines()  
        for line in POS:  
        columns=line.split()  
        query=columns[0]  
        locate=(int(columns[1])-1)  
        newnuc=columns[2]  
        oldnuc=columns[3]  
        with open ("FILE2.txt")as f:  
            Sequo=f.readlines()  
            for linex in Sequo:  
                columnos=linex.split()  
                querios=columnos[0]  
                sequence=columnos[1]  
                if query == querios:  
                    newseqons= sequence [:locate] + newnuc + sequence [locate + 1:]  
                    print(newseqons)  

这是我的新代码,PATRICK

 with open (r'C:\Users\Administrator\Desktop\Sequorro.txt') as f2:
     Sequo=f2.readlines()
     for linex in Sequo:
         columnos=linex.split()
         querios=columnos[0]
         sequence=columnos[1]
         d={}
         d.update({querios: sequence})
         print(d)
{'CRUP_004407-RA': 'AAAAAAAAA'}
{'CRUP_004416-RA': 'GGGGGGGGG'}


with open (r'C:\Users\Administrator\Desktop\POS.txt') as f1:
    POS=f1.readlines()
    for line in POS:
        columns=line.split()
        query=columns[0]
        locate=(int(columns[1]))
        newnuc=columns[2]
        oldnuc=columns[3]
        oldstr=d[querios]
        d[querios]=oldstr[:locate-1] +newnuc +oldstr[locate:]
        print(d)

{'CRUP_004416-RA': 'GCGGGGGGG'}
{'CRUP_004416-RA': 'GCGGGGGGG'}
{'CRUP_004416-RA': 'GCGGGTGGG'}
{'CRUP_004416-RA': 'GCCGGTGGG'}
{'CRUP_004416-RA': 'GCCAGTGGG'}
{'CRUP_004416-RA': 'GCCAGTTGG'}

with open (r'C:\Users\Administrator\Desktop\Sequorooo.txt','w') as f2:
    for querios, sequence in sorted(d.items()):
        f2.write('{}{}'.format(querios, sequence))
        f2.close()

CRUP_004416-RAGCCAGTTGG

1 个答案:

答案 0 :(得分:1)

with open('file2') as f2:
    d = {name: string_ for line in f2 for name, string_ in (line.split(),)}
    #Build a dictionary of names mapped to strings from the 2nd file

with open('file1') as f1:
    #Do the replacements on the dictionary for the rules in file1
    for line in f1:
        name, pos, rep, *_ = line.split()
        oldstr = d[name]
        d[name] = oldstr[:pos-1] + rep + oldstr[pos:]

with open('file2', 'w') as f2:
    for name, string_ in sorted(d.items()): 
        #Write the new strings and names back to the file
        f2.write('{} {}'.format(name, string_))