簡體   English   中英

我無法正確使用枚舉功能

[英]I am not able to use enumerate function properly

我已經編寫了一個代碼來從文本文件(從pdf復制的簡單文本文檔)中枚舉char“ 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 

但是當我用“ output_f.write()”在文本文件“ svm_in.txt”中寫下輸出時,輸出是非常有線的。 像這樣的事情:

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 

不要打印換行符,而是將它們寫到文件中:

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()您可以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))

巧妙地避免了拖尾空間。

我會這樣做:

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)

您可以修改最后一行中的字符串,以控制該行將如何寫入輸出文件中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM