2017-07-19 54 views
0

TXT」其中有很多在線路的IP地址,如下對比IP的從一個文件到另一

10.2.3.4 
10.5.6.7 
10.8.6.8 
10.80.67.1 
10.66.77.2 
10.86.98.9 

和其他文件b.txt

10.5.6.7 
10.33.56.2 
10.55.78.5 
10.86.98.3 

現在我想在寫代碼python,以便b.txt IP基於三個八位組中的相同值與a.txt文件中的IP地址進行比較。

,使輸出可以是一個這是不是在a.txt中,所以輸出將低於因爲這兩個IP地址的三個字節不匹配任何A.TXT文件

10.33.56.2 
10.55.78.5 

提前致謝。

file1 = open(r'a.txt', 'r') 
file2 = open(r'b', 'r') 
FO = open(r'c.txt', 'w') 
data = file1.read() 
my_list = data.splitlines('10.') 
for i in my_list: 
    j = my_list[0:4] 
    print(j) 
+1

那你試試這麼遠嗎? –

+0

的file1 =開放(r'a.txt ' 'R') file2的開放=(r'b,TXT 'R') FO =開放(r'c.txt', 'W') 數據= file2.read() my_list = data.splitlines('10') 因爲我在my_list: J = my_list [0:4] 打印(J) – PSK

+2

編輯你的問題,而不是發佈你的代碼爲評論 – Ludisposed

回答

0

把你的IP地址從一組:

ip_a = set(line.split(' ').strip()) # Or 3 first bytes if you prefer 

下一頁每個IP B中

if ip_in_b not in ip_a: # Or 3 first bytes 
    print(ip_in_b) 
+0

謝謝本傑明,我還沒有嘗試過這仍然是由我的要求由Ludisposed提供的代碼實現的。但是現在我正在尋找它的基於IP地址OCTET的選項......例如,使用10.5.6。搜索其他列表中是否有匹配。 – PSK

+0

字節在我的答案中表示八位字節 – Benjamin

0

嘗試與with open打開文件... as,因爲在你當前的代碼中,你只能打開它們而不是關閉。這樣它會在完成打開文件時自動關閉。

with open('a.txt','r') as f: 
    output_a = [i for i in f] 
with open('b.txt','r') as f: 
    output_b = [i for i in f] 

2. 爲了能夠找到如果三個字節與其他一些知識產權的,你可以做這樣的事情的清單:

# Testdata 
output_a = ['1.1.2.9', '1.5.65.32'] 
output_b = ['1.2.57.1', '1.5.65.39'] 

# This will check if any subIP is in the list of other ip's and if not will append to result 
# The rest I leave up to you ;) 

# First solution 
result = [] 
subIP = lambda x: ['.'.join(i.split('.')[:3]) for i in x] 
for sub, full in zip(subIP(output_a), output_a): 
    if not len([ip for ip in subIP(output_b) if sub == ip]): 
     result.append(full) 
print(result) 
# Will print: ['1.1.2.9'] 

# Second solution 
# Some set operations will also work, but will leave you with a set of ip with 3 octets 
# afterwards you need to convert it back to full length if you want 
print (set(subIP(output_a)) - set(subIP(output_b))) 
# Will print {'1.1.2'} 
+0

感謝Ludisposed,它的工作原理是找出不在a.txt中的IP列表。但是我還有一個問題,我們可以根據IP地址OCTET找到選項......例如,使用10.5.6。搜索其他列表中是否有匹配。 – PSK

+1

如果我的答案是有用的,請註冊並標記爲答案。這樣你可以贏得一些聲譽並保持網站內容的高度 – Ludisposed

相關問題