我不能正确使用枚举函数

2024-10-01 19:23:56 发布

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

我写了一段代码,从文本文件(从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 

Tags: ofthe代码intxthomeforinput
2条回答

我会这样做:

for line in input_f:

    # find the positions of As in the line
    positions = [n for n, letter in enumerate(line, 1) if letter == 'a']

    # Create list of strings of the form "x:y"
    pairs = [("%d:%d" % (i, n)) for i, n in enumerate(positions, 1)]

    # Join all those strings into a single space-separated string
    all_pairs = ' '.join(pairs)

    # Write the string to the file, with a + sign at the beginning
    # and a newline at the end
    output_f.write("+ %s\n" % all_pairs)

您可以修改最后一行中的字符串,以控制如何在输出文件中写入该行。你知道吗

不要打印换行符,而是将它们写入文件:

for line in input_f :
    output_f.write("\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))
        output_f.write(a + " ")        

您可以使用一些元组解包来更清楚地说明您正在枚举的内容,并且可以删除[..]列表理解,改用生成器表达式(节省一些内存和处理):

for i, pos in enumerate((pos for pos, char in enumerate(line, 1) if char == 'a'), 1):
    output_f.write('%d:%d ' % (i, pos))

我还为enumerate()函数提供了第二个参数,即起始值,这样就不必+ 1每个数字,并在字符串格式的文件输出中添加了空格。你知道吗

通常在写一行之后写一个换行符;如果每行需要一个计数器,请添加另一个枚举:

for count, line in enumerate(input_f, 1):
    output_f.write("%d+ " % count)
    for i, pos in enumerate((pos for pos, char in enumerate(line, 1) if char == 'a'), 1):
        output_f.write('%d:%d ' % (i, pos))
    output_f.write('\n')

或者,通过使用str.join(),您可以一次性创建一整行,使用格式化在一个格式化操作中包含前缀和换行符:

for count, line in enumerate(input_f, 1):
    positions = (pos for pos, char in enumerate(line, 1) if char == 'a')
    line = ' '.join(['%d:%d' % (i, pos) for i, pos in enumerate(positions, 1)])
    output_f.write("%d+ %s\n" % (count, line))

这也巧妙地避免了尾随空格。你知道吗

相关问题 更多 >

    热门问题