2017-05-07 151 views
1

我與蟒蛇正則表達式的工作,下面的代碼似乎不起作用蟒蛇正則表達式組AttributteError

import re                                                          
# my regular expressions                         
exprs = [ r"Gene ID: (.*)\,", r"(.*)\[Homo sapiens]",                    
      r"from:(.*)\s", r"NM_(.*)\.([0-9]+)" ,                     
      r"NP_(.*)\.([0-9]+)\s", r"\,(.*)[^coding]exons",                   
      r"AA length:(.*)\s", r"isoform(.*)\\NP" ]                                                
# search for expressions vector in genetable                    
with open('massaCHD8.txt', "r") as df:                      
    arq = df.read()                          
for element in exprs:                          
    resu = re.findall(element, arq, re.M|re.I)                    
    for el in resu:                            
     print(resu.group(0))                               

當我運行以下scritpt我得到了以下錯誤:

Traceback (most recent call last): File "io2.py", line 17, in print(resu.group(0)) AttributeError: 'list' object has no attribute 'group'

+0

https://docs.python.org/3/library/re.html#re.findall – handle

回答

0

re.findall返回找到的字符串/元組列表,而不是Match對象。因此,如果你要打印的比賽,你可以使用:

for element in exprs:                          
    resu = re.findall(element, arq, re.M|re.I)                    
    for el in resu:                            
     print(el if isinstance(el, str) else el[0]) 
+0

>如果一個或多個組存在在該模式中,返回一個組列表;如果模式有多個組,這將是一個元組列表。 – handle

0

嘗試

import re                                                          
# my regular expressions                         
exprs = [ r"Gene ID: (.*)\,", r"(.*)\[Homo sapiens]",                    
      r"from:(.*)\s", r"NM_(.*)\.([0-9]+)" ,                     
      r"NP_(.*)\.([0-9]+)\s", r"\,(.*)[^coding]exons",                   
      r"AA length:(.*)\s", r"isoform(.*)\\NP" ]                                                
# search for expressions vector in genetable                    
with open('massaCHD8.txt', "r") as df:                      
    arq = df.read()                          
for element in exprs:                          
    resu = re.findall(element, arq, re.M|re.I)                    
    for el in resu:                            
     print(el)