我写了一段代码,从文本文件(从pdf复制的简单文本文档)枚举字符“a”:
input_f = open('/home/zebrafish/Desktop/stackq/doc.txt','r')
#text i used in "doc.txt file"
#
#unctional similarities between the ATP binding pockets of
#kinases or between chemotypes of inhibitors that cannot
#be predicted from the sequence of the kinase or the
#chemical structure of the inhibitor.
#We first compared PI3-K family members according to
output_f = open('/home/zebrafish/Desktop/stackq/svm_in.txt','w')
for line in input_f :
a = line
print "\n",
for y in enumerate([x[0] for x in enumerate(line) if x[1]=='a']):
a = ("%d:%d" % (y[0]+1,y[1]+1))
#print a,
output_f.write(a+" ")
input_f.close()
output_f.close()
如果我运行这个脚本而没有按照我的要求生成输出文件,那么这个代码的输出是这样的,对于每一行,它都会计算“a”的位置和频率,如第一行“a”出现两次,第一次出现在第8位,第二次出现在第16位,因此被枚举为“1:8 2:16”,因此每行一个:
1:8 2:16
1:4 2:47 3:51
1:42
1:7
1:14 2:26 3:40
但是当我把输出写进一个文本文件“svm_在.txt中“output\ f.write()”的输出非常有线。 像这样的事情:
1:8 2:16 1:4 2:47 3:51 1:42 1:7 1:14 2:26 3:40
如何在输出文件中为每一行首有“+”正弦的行生成结果,如下所示:
+ 1:8 2:16
+ 1:4 2:47 3:51
+ 1:42
+ 1:7
+ 1:14 2:26 3:40
我会这样做:
您可以修改最后一行中的字符串,以控制如何在输出文件中写入该行。你知道吗
不要打印换行符,而是将它们写入文件:
您可以使用一些元组解包来更清楚地说明您正在枚举的内容,并且可以删除
[..]
列表理解,改用生成器表达式(节省一些内存和处理):我还为
enumerate()
函数提供了第二个参数,即起始值,这样就不必+ 1
每个数字,并在字符串格式的文件输出中添加了空格。你知道吗通常在写一行之后写一个换行符;如果每行需要一个计数器,请添加另一个枚举:
或者,通过使用
str.join()
,您可以一次性创建一整行,使用格式化在一个格式化操作中包含前缀和换行符:这也巧妙地避免了尾随空格。你知道吗
相关问题 更多 >
编程相关推荐