2016-07-13 92 views
1

我想我发现了一个类似的问题在这里(Python search a file for text using input from another file),但似乎并没有为我工作,打印为空,在没有找到,但他们definitley匹配所有搜索文本文件与另一个文本文件

源文件样本:

MAC Address  
0800.0f5b.b739 
0800.0f69.d860 
0800.0f6b.9177 
0800.0f6c.2e4d 
0800.0f77.2879 
0800.0f7f.4c07 
0800.0f83.4785 
0800.0f9c.f608 

数据文件样本:

MAC Address  IP Address 
000c.2912.57db 10.1.7.254 
000c.294a.4b75 10.1.7.253 
002a.6a5e.e381 10.1.6.3 
0050.56ac.5f41 10.1.7.8 
0050.56ac.5f41 10.1.7.9 
0050.56ac.6067 10.1.6.249 
0050.56ac.6067 10.1.6.254 
0050.56ac.9d49 10.1.7.104 
0800.0f5b.b739 10.1.7.153 
0050.56ac.e9c9 10.1.7.250 
0800.0f48.7f40 10.1.6.180 
0800.0f51.9d99 10.1.6.112 
0800.0f51.a32a 10.1.6.47 
0800.0f51.a915 10.1.6.241 

使用我想找到从数据文件中匹配的IP地址源文件。我试图从另一个问题,看到的样品

d_file = 'C:\Python Scripts\VLAN_Data.txt' 
s_file = 'C:\Python Scripts\SourceData.txt' 

keywords = set() 
with open(s_file) as list_file: 
    for line in list_file: 
     if line.strip(): 
      keywords.add(line.strip()) 

with open(d_file) as master_file: 
     for line in master_file: 
      if set(line.split()[:-1]) & keywords: 
       print line 

编辑

确定它的工作....我是复制和粘贴到外壳和失败,我救它作为一个的.py和在模块中运行它,而它的工作原理。任何人都知道为什么将意大利面复制到壳上会失败

+0

*“失败”*的任何提前? – jonrsharpe

+0

编辑 - 失败,因为没有结果 – AlexW

+2

你说的数据样本有多大?你能否将数据文件作为字典读入内存? – Lost

回答

2

这是我应该怎样做:

with open(r'C:\Users\evkouni\Desktop\file_sample.txt', 'r') as f_in: 
    content = f_in.readlines() 
    add_dict = {} 
    for line in content: 
     add_dict[line.split()[0]] = line.split()[1] 

with open(r'C:\Users\evkouni\Desktop\target.txt', 'r') as f_t: 
    content = f_t.readlines() 
    matches = {} 
    for line in content: 
     if line.strip() in add_dict: 
      matches[line.strip()] = add_dict[line.strip()] 
      continue 

print(matches) 
#{'0800.0f5b.b739': '10.1.7.153'} 

第一with块加载MAC到IP地址块,并存储对在字典中add_dict

第二with块打开目标文件,并通过它行由线变为搜索预先存储的密钥。当它发现它们时,它将这对存储在一个叫做matches的新字典中。容器类型matches取决于您计划如何处理它。

1

为另一种解决方案是:

d_file = 'Data\data.txt' 
s_file = 'Data\source.txt' 

keywords = set() 
with open(s_file) as list_file: 
    for line in list_file: 
     if line.strip(): 
      keywords.add(line.strip()) 

data = set() 
with open(d_file) as master_file: 
     for line in master_file: 
      data.add(line.strip().split(' ')[0]) 

print keywords.issubset(data) 

该解决方案是基于set路口:创建两个组的MAC寻址,并检查是否一个完全包含在另一个。