2014-11-24 77 views
0

我對Python的世界相當新鮮,感覺好像我過分複雜了我製作的腳本,是否有任何方法可以簡化或可以合併的任何技術我不知道? (道歉,如果這是過於含糊)Elegancy/Succinct腳本編寫

#!/usr/bin/python 
import sys, urllib2, re 
es="http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=protein&term="+sys.argv[1] 
ef="http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=protein&id=" 
url=urllib2.urlopen(es) 
match=url.readlines() 
print "<head>" 
print "<style>" 
print "table, th, td {" 
print " border: 1px solid black;" 
print "}" 
print "</style>" 
print "</head>" 
print "<body>" 
print "<table>" 
print "<tr>" 
print "<th>GI number</th>" 
print "<th>ID</th>" 
print "<th>Nucleotide sequence</th>" 
print "</tr>" 
for line in match: 
    col1=re.search(r'<Id>(.*)</Id>',line) 
    if col1: 
    fetch=ef+col1.group(1)+"&rettype=fasta&retmode=xml" 
    urlf=urllib2.urlopen(fetch) 
    print "<tr>" 
    print "<th>" 
    print "<a href=\"http://www.ncbi.nlm.nih.gov/protein/"+col1.group(1)+"\">"+col1.group(1) 
    print "</a>" 
    print "</th>" 
    pline="".join(urlf.readlines()) 
    col2=re.search(r'<TSeq_sequence>(.*)</TSeq_sequence>',pline) 
    col3=re.search(r'<TSeq_defline>(.*)</TSeq_defline>',pline) 
    if col3: 
     print "<td>" 
     print col3.group(1) 
     print "</td>" 
     ltot=(len(col2.group(1))/40)+1 
     ln=0 
     print "<td>" 
     while ln<=ltot: 
     bnd1=ln*40 
     bnd2=(ln+1)*40 
     print col2.group(1)[bnd1:bnd2] 
    ln+=1 
    print "</tr>" 
print "</body>" 
print "</table>" 
+3

是的,字符串模板。 – 2014-11-24 23:58:45

+0

縮進不正確。 – wflynny 2014-11-24 23:59:56

+4

這個問題可能更適合[CodeReview](http://codereview.stackexchange.com/)。 – csmckelvey 2014-11-25 00:03:41

回答

0

而不是使用的打印線的HTML每一行代碼,你可以創建一個使用多行字符串,如大塊的代碼:

topSection = """<head> 
    <style> 
    table, th, td { 
     border: 1px solid black; 
    } 
    </style> 
</head> 
<body> 
    <table> 
    <tr> 
     <th>GI number</th> 
     <th>ID</th> 
     <th>Nucleotide sequence</th> 
    </tr>""" 

對於需要一些值進行編程插入您可以使用格式字符串的方法,例如HTML代碼段:

variable1 = "some value" 
variable2 = "some other value" 
htmlsection = """<HTML CODE> 
<MORE HTML CODE> 
<MORE HTML CODE> 
<HTML CODE WITH A VARIABLE VALUE = {0}> 
<HTML CODE WITH ANOTHER VARIABLE VALUE = {0}>""".format(variable1, variable2) 

然後,您可以串接所有字符串組成部分和只需使用一條打印語句:

print(topSection + middleSection + endSection)