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

2024-10-01 07:18:42 发布

您现在位置:Python中文网/ 问答频道 /正文

一天多来我一直在寻找一种方法,但没能找到我真正需要的。我有两个文件。第一个文件的名字在第二列,字母在第三列。在第二个文件中,第一列是名称,第二列是字符串。我有一个循环,它遍历第一个文件中的每一行,将名称与每一行中的第二个文件匹配,然后转到位置并使用字母更改字符串。循环工作得很好,但我不能为下一封信保留更改。你知道吗

就像

第一个文件

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

第二个文件

NAME1   AAAAAAAAA
NAME2   BBBBBBB

我使用STRING作为输入,并在循环期间使用更改的字母创建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)  

这是我的新密码,帕特里克

 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

Tags: columns文件inpostxtforaswith
1条回答
网友
1楼 · 发布于 2024-10-01 07:18:42
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_))

相关问题 更多 >