提取角色的侧向区域

2024-09-25 00:27:16 发布

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

我试着在一行中定位一个特殊的字符“r”,然后检索它两侧的35个字符。可能不止一个“r”,所以我正在尝试获取所有的r。我一直在尝试这个代码,但我只得到了标题,我不能搞清楚。有什么建议吗

fhand=open("input.txt")
target = open ("output.txt", "a")
for line in fhand:
    name, id, seq= line.split("\t")
    while atpos < len(seq):
        if atpos == -1:
            break
        atpos = seq.find ("r")
        seq2 = seq[(atpos-35):(atpos+36)]
        line2= name + "\t"+ id + "\t" + seq2 + "\n"
        target.write(line2)
        atpos += 1

print ("Sequences obtained successfully")
target.close()

Tags: 代码name定位txtidtargetlineopen
1条回答
网友
1楼 · 发布于 2024-09-25 00:27:16
import csv

with open("input.txt") as infile, open('output.txt', 'w') as fout:
    outfile = csv.writer(fout, delimiter='\t')
    for name, id, seq in csv.reader(infile, delimiter='\t'):
        locs = [i for i,char in enumerate(seq) if char=='r']
        for loc in locs:
            outfile.writerow([name, id, seq[max(loc-35, 0) : loc+36]])

相关问题 更多 >