搜索一个文本文件与另一个文本文件

2024-10-01 17:31:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我以为我在这里发现了一个类似的问题(Python search a file for text using input from another file),但这似乎对我不起作用,打印内容是空的,就像在none found中一样,但它们都有明确的匹配项

源文件示例是:

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  

编辑

好的,它确实工作了…我复制并粘贴到shell中,但失败了,我将它保存为.py并在模块中运行它,结果它工作了。有人知道为什么把意大利面复制到贝壳里会失败吗?你知道吗


Tags: txt示例foraddressmac数据文件linescripts
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-to-IP地址块,并将对存储在字典add_dict中。你知道吗

第二个with块打开目标文件并逐行搜索先前存储的键。当它找到它们时,它会将这一对存储在一个名为matches的新dict上。容器的类型matches取决于您打算用它做什么。你知道吗

另一个解决方案是:

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地址集,并检查其中一个是否完全包含在另一个中。你知道吗

相关问题 更多 >

    热门问题