2017-01-11 5 views
1

バルクテキストから電子メールアドレスとIPアドレスを抽出するコードを書きました。ただし、コードは電子メールアドレスのみを抽出します。 (理解できるようにする元のテキストは、典型的なログファイルです)私はなぜ生成されたファイルが私にIPアドレスを返さないのかわかりません。Python - Regex - IP - no result

import os 
import re 

# 1 
filename = 'errors.txt' 
newfilename = 'emaillist-rev.txt' 

# 2 
if os.path.exists(filename): 
    data = open(filename,'r') 
    bulkemails = data.read() 


else: 
    print "File not found." 
    raise SystemExit 

# 3 
r = re.compile(r'[\w\.-][email protected][\w\.-]+') 
results = r.findall(bulkemails)  

emails = "" 
for x in results: 
    emails += str(x)+"\n" 


# 4 
ip = re.compile('^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$') 
result = ip.findall(bulkemails) 

ip ="" 
for y in result: 
    ip += str(y)+"\n" 

# 5 
def writefile(): 
    f = open(newfilename, 'w') 
    f.write(emails + ip) 
    f.close() 
    print "File written." 

# 6 
def overwrite_ok(): 
    response = raw_input("Are you sure you want to overwrite "+str(newfilename)+"? Yes or No\n") 
    if response == "Yes": 
     writefile() 
    elif response == "No": 
     print "Aborted." 
    else: 
     print "Please enter Yes or No." 
     overwrite_ok() 

# 7 
if os.path.exists(newfilename): 
    overwrite_ok()  
else: 
    writefile() 
+1

アンカーをワード境界で置き換えます。-i = re.compile(r '\ b \ d {1,3} \。\ d {1,3} \。\ d {1,3} \ 。\ d {1,3} \ b ') 'となります。生の文字列リテラルを使用する必要があります。 –

+0

解決済み!助けをたくさんありがとう:) – ForbiddenVikings

+0

助けてくれてうれしい、いくつかの8分で私の答えを受け入れることを検討してください。 –

答えて

0

ip正規表現を宣言するとき、あなたは文字通り生の文字列を使用する必要がワード境界と心でアンカーを交換してください。

ip = re.compile(r'\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b')