2016-03-28 18 views
0

regex ifadesinden okunan dizeleri yazdırmaya çalışıyorum. Regex arama ile okunan metnin bazı satırları için, hiçbir veri yok, bu yüzden okunacak bir şey yok. Bu olduğunda, "AttributeError: 'NoneType' object has no attribute 'group' hatasını aldım. Kimse benim kodumda bir çalışma yazmama yardımcı olabilir, böylece normal ifadeden hiçbir şey okunmazsa değişken yazdırılmaz? if (col3.group() != None):'u denedim, ancak işe yaramıyor. Senin durumundaWorkaround Hayır Değişken Okuma İçinde Regex Ara

match = re.search(expression, string, flags) 
if match: # match would be None if there is no match 
    print(match.group()) 

:

#!/usr/bin/env python 

#purpose of script: To conduct an nslookup on a list of IP addresses 

import os, csv, re 

#get list of IP's from file 
inFile='filesystem/Book1.txt' 
ipList = [] 
with open(inFile, 'rb') as fi: 
    for line in fi: 
     line = line.replace(',', '')#remove commas and \n from list 
     line = line.replace('\r', '') 
     line = line.replace('\n', '') 
     ipList.append(line)# create list of IP addresses to lookup 

#output results 
outFile='filesystem/outFile.txt' 
fo = open(outFile, 'w') 
inc=0 
writeToFileValue = "" 
for e in ipList: 
    result = os.popen('nslookup ' + e).read()#send nsLookup command to cmd prompt 

    col1 = re.search(r'Server:.*', result, re.M|re.I)#use regex to extract data 
    col2 = re.search(r'Address: 8.8.8.8', result, re.M|re.I) 
    col3 = re.search(r'Name:.*', result, re.M|re.I) 
    col4 = re.search(r'Address: (?!8.8.8.8).*', result, re.M|re.I) 

    print col1.group() 
    print col2.group() 
    if (col3.group() != None): 
     print col3.group() # if none, skip 
    if (col4.group() != None): 
     print col4.group() # if none, skip 
+0

Traceback'i gösterebilir misiniz? AttributeError hangi satırı alırsınız? –

cevap

1

:

if (col3.group() != None): 
     print col3.group() # if none, skip 

bunu yapın:

try col3.group(): 
     print col3.group() 
    except AttributeError: 
     pass 
1

Yaygın bir kalıptır burada,

col1 = re.search(r'Server:.*', result, re.M|re.I) 
if col1: 
    print(col1.group()) 

Veya, bir örnektir nasıl maçların tümü üzerinde döngü ve bir varsayılan belirlemek eşleşme yoksa boş dize değeri:

matches = [col1, col2, col3, col4] 
print([match.group() if match else "" 
     for match in matches]) 

Bu arada, burada güvenli ve kısa bir şekilde yakalanan grup ayıklamak için nasıl bir ilgili iplik:

1

: Bu yerine

if (col3 is not None): 
    print col3.group() 
if (col4.group() is not None): 
    print col4.group()