我正在了解如何比较两个文本文件中的数据,并将不匹配的数据打印到新文档或输出中。你知道吗
假设我有以下文本文档,其中包含这些参数和数据: 叫它吧配置.txt地址:
<231931844151>
Bird = 3
Cat = 4
Dog = 5
Bat = 10
Tiger = 11
Fish = 16
<92103884812>
Bird = 4
Cat = 40
Dog = 10
Bat = Null
Tiger = 19
Fish = 24
etc. etc.
让我们称之为我的配置数据,现在我需要确保配置数据文件中这些参数的值是正确的。你知道吗
所以我有一个默认的数据文件,它有这些参数/变量的正确值。叫它吧默认.txt你知道吗
<Correct Parameters>
Bird = 3
Cat = 40
Dog = 10
Bat = 10
Tiger = 19
Fish = 234
此文本文件是数据的默认配置或正确配置。你知道吗
现在我要比较这两个文件并打印出不正确的数据。你知道吗
所以,理论上,如果我要比较这两个文本文档,我应该得到以下结果:我们称之为输出.txt你知道吗
<231931844151>
Cat = 4
Dog = 5
Tiger = 11
Fish = 16
<92103884812>
Bird = 4
Bat = Null
Fish = 24
etc. etc.
因为这些参数不正确或不匹配。因此在本例中,我们看到对于<;231931844151>;而言,参数Cat、Dog、Tiger和Fish与默认文本文件不匹配,因此将打印这些参数。如果<;92103884812>;鸟、蝙蝠和鱼与默认参数不匹配,则会打印这些参数。
所以这就是现在的要点。你知道吗
目前这是我的方法,我正在尝试做,但我不知道如何比较一个数据文件,我有不同的行相同的参数设置到一个默认的数据文件。你知道吗
configFile = open("Config.txt", "rb")
defaultFile = open("Default.txt", "rb")
with open(configFile) as f:
dataConfig = f.read().splitlines()
with open(defaultFile) as d:
dataDefault = d.read().splitlines()
def make_dict(data):
return dict((line.split(None, 1)[0], line) for line in data)
defdict = make_dict(dataDefault)
outdict = make_dict(dataConfig)
#Create a sorted list containing all the keys
allkeys = sorted(set(defdict) | set(outdict))
#print allkeys
difflines = []
for key in allkeys:
indef = key in defdict
inout = key in outdict
if indef and not inout:
difflines.append(defdict[key])
elif inout and not indef:
difflines.append(outdict[key])
else:
#key must be in both dicts
defval = defdict[key]
outval = outdict[key]
if outval != defval:
difflines.append(outval)
for line in difflines:
print line
我想比较两个包含数据/参数的文本文档,一个文本文档包含一系列具有相同参数的数据,而另一个文本文档仅包含一系列具有相同参数的数据。我需要比较这些参数并打印出与默认值不匹配的参数。我怎样才能用Python来做这个呢?你知道吗
好吧,多亏了@Maria的代码,我想我就快到了。现在我只需要找出如何将字典与列表进行比较,并打印出差异。下面是我想做的一个例子:
for i in range (len(setNames)):
print setNames[i]
for k in setData[i]:
if k in dataDefault:
print dataDefault
很明显,打印行只是为了看看它是否有效,但我不确定这是否是正确的方式来通过这个。你知道吗
为什么不直接使用这些dict并循环使用它们来比较呢?你知道吗
将文件解析为单独字典的示例代码。这是通过查找组分隔符(空行)来实现的。setNames[i]是字典中setData[i]处的一组参数的名称。或者,您可以创建一个对象,该对象具有字符串
name
成员和字典data
成员,并保留这些成员的列表。进行比较并按自己的意愿输出,这只是将输入文件以稍微不同的格式返回到命令行。你知道吗相关问题 更多 >
编程相关推荐