python-3.x - Python str.replace 问题:每次替换字符串后都会插入换行符
问题描述
我需要编辑一个 gff 文件的基因名称,如下所示。原始文件:
chr1 aug gene 10708 108196 . - . ID=gene:g754;biotype=protein_coding
chr1 aug exon 10708 107528 . - . Parent=transcript:g754;Name=g754_T001.exon.1;exon_id=g754_T001.exon.1
chr1 aug gene 20588 20898 . - . ID=gene:g756;biotype=protein_coding
chr1 aug mRNA 20588 20898 . - . ID=transcript:g756;Parent=gene:g756;biotype=protein_coding;transcript_id=g756_T001
chr1 aug exon 20588 20690 . - . Parent=transcript:g756_T001;Name=g756_T001.exon.1;exon_id=g756_T001.exon.1
新文件:
chr1 aug gene 10708 108196 . - . ID=gene:Gene00001;biotype=protein_coding
chr1 aug exon 10708 107528 . - . Parent=transcript:Gene00001;Name=Gene00001_T001.exon.1;exon_id=Gene00001_T001.exon.1
chr1 aug gene 20588 20898 . - . ID=gene:Gene00002;biotype=protein_coding
chr1 aug mRNA 20588 20898 . - . ID=transcript:Gene00002;Parent=gene:Gene00002;biotype=protein_coding;transcript_id=Gene00002_T001
chr1 aug exon 20588 20690 . - . Parent=transcript:Gene00002_T001;Name=Gene00002_T001.exon.1;exon_id=Gene00002_T001.exon.1
作为输入,我有 gff 文件和一个包含当前和新基因名称键的列表。
g754 Gene00001
g756 Gene00002
我在 python 中编写了一个脚本,用新的基因名称替换旧的基因名称。replace 命令按预期工作,但每次替换字符串后都会插入一个换行符。我不知道为什么会这样,谷歌让我失望了。我确实尝试在这里模仿解决方案:在 gffile 中重命名名称 ID。,但我有一个单独的基因名称密钥文件。我正在使用 anaconda/python3.6
当前代码:
import sys
import getopt
import operator
in_gff = open("current_gff_file.gff3", "r")
out_gff = open("new_file.gff", "w")
name_key = open("name_key_file.txt", "r")
current_name = []
new_name = []
#create 2 lists of current and new names
for name_row in name_key:
name_field = name_row.split("\t")
current_name.append(name_field[0])
new_name.append(name_field[1])
for row in in_gff:
line = row.rstrip()
if line.startswith("#"):
print(line, file = out_gff, end = "\n") #if it is a header line just print to new file
else: #loop through list of current gene names
for name in range(len(current_name)):
if current_name[name] in line:
new_line = line.replace(current_name[name], new_name[name])
print(new_line) #test loop by printing to screen, line breaks happen after every string replacement
#Output I want: ID=transcript:Gene00002;Parent=gene:Gene00002;biotype=protein_coding;transcript_id=Gene00002_T001
#Output I get: ID=transcript:Gene00002
#Parent=gene:Gene00002
#biotype=protein_coding;transcript_id=Gene00002
#_T001
else:
continue
解决方案
遍历文件时,每一行仍包含结尾的换行符。在构建翻译表时将其删除:
for name_row in name_key:
name_field = name_row.split("\t")
current_name.append(name_field[0])
new_name.append(name_field[1].strip('\n')) # store stripped names only
推荐阅读
- mysql - 如何打开 .exp 文件?
- android - AAR 文件中的类在 Android Studio 中不可用
- vb.net - 如果空行,Streamreader 读取下一行
- ios - 应用程序加载器/Xcode 卡在“使用 App Store 验证资产”上
- ios - 极坐标点生成函数的上界不是 2Pi 的 theta 吗?
- c# - ASP.NET MVC 根据用户角色显示 HTML
- excel - 在 Calc 中,我可以使用与另一个单元格相关的代码填充一个单元格吗?
- c - C 为空时删除链表的节点
- java - gradle和junit的间歇性并发失败
- rasa-nlu - 如何 curl 访问 RASA NLU(starter-pack-rasa-stack)?