我正在尝试处理一个 CSV 文件并提取主机名并将提取保存到一个名为的文件中host_file1,然后将此文件与现有的文本文件进行比较,即host_file2,因此 csv 处理工作正常。现在,正如我所说,我想在两个文件之间进行一些主机名比较,我想要的是将主机名host_file2与匹配host_file1,因此如果主机名在host_file2但不在host_file1打印主机名中,请不要打印两者中的主机名文件。我已经尝试过类似下面的设置,但它只是给出了我想要的不同。#!/python/v3.6.1/bin/python3from __future__ import print_functionfrom signal import signal, SIGPIPE, SIG_DFLsignal(SIGPIPE,SIG_DFL)import pandas as pd##### Python pandas, widen output display to see more columns. ####pd.set_option('display.height', None)pd.set_option('display.max_rows', None)pd.set_option('display.max_columns', None)pd.set_option('display.width', None)pd.set_option('expand_frame_repr', True)##################### END OF THE Display Settings ###################df_csv = pd.read_csv(input("Please input the CSV File Name: "), usecols=['Platform ID', 'Target system address']).dropna()hostData = df_csv[df_csv['Platform ID'].str.startswith("CDS-Unix")]['Target system address']hostData.to_csv('host_file1', header=None, index=None, sep=' ', mode='a')with open('host_file1', 'r') as f: dataset1 = set(f)with open('host_file2', 'r') as f: dataset2 = set(f)for i, item in enumerate(sorted(dataset1 ^ dataset2)): print(str(item))# shorter"""with open('host_file1') as f1, open('host_file2') as f2: dataset1 = set(f1) dataset2 = set(f2)"""两个不同的主机名文件:主机文件1vmhost01vmhost02vmhost03vmhost04vmhost05vmhost06vmhost07vmhost08vmhost09vmhost10主机文件2vmhost01vmhost02vmhost03vmhost04vmhost05vmserver01vmhost07vmhost08vmserver02vmhost10想要的结果:vmserver01vmserver02
3 回答
白衣染霜花
TA贡献1796条经验 获得超10个赞
我认为你需要减法集:
for i, item in enumerate(sorted(dataset2 - dataset1)):
#alternative
#for i, item in enumerate(sorted(dataset2.difference(dataset1))):
print(str(item))
vmhost01
vmhost02
vmserver01
vmserver02
和列表理解的最后一个解决方案:
s = set(dataset1)
out = [x for x in dataset2 if x not in s]
print (out)
['vmserver02', 'vmhost02', 'vmhost01', 'vmserver01']
添加回答
举报
0/150
提交
取消