如何使用 Python 从给定的文本文件向字典添加 table?

How to add a table to dictionary from a given text file using Python?

假设我们有两个文本文件,每个文件都包含一个 table,例如:

table1.txt

a: 1
b: 2
c: 3
b: 4

table2.txt

a: 1
b: 2
c: 3
b: 5

我想将那些 table 添加到 Python 词典中,然后比较条目,以便将不匹配的结果转储到输出文件中。在上面的例子中

output.txt

b:4 | b:5

感谢您的意见!

我会这样做:

t1, t2 = [], []

# below, we read data in from both files.
with open("table1.txt", "r") as f:
    t1 = f.read().split("\n")
with open("table2.txt", "r") as f:
    t2 = f.read().split("\n")

t12 = []
for i in t1:
    for j in t2:
        vals = i.split(":"), j.split(":") # we split up the key and value from each file.
        if vals[0][0] == vals[1][0]: # i.e. if the keys are the same
            t12.append(f"{vals[0][0]}: {vals[0][1]} | {vals[1][0]}: {vals[1][1]}\n") # create a new string that combines both values.

# writing to the new file
with open("tables_combined.txt", "w") as f:
    for i in t12:
        f.write(i)

我可能会将每个文件读入它们自己的字典中。所以读取文件,将字母指定为键,将数字指定为值,这意味着你得到两个字典:

dict1 = {
  "a": 1,
  "b": 2,
  "c": 3,
  "d": 4
}

dict2 = {
  "a": 1,
  "b": 2,
  "c": 3,
  "d": 5
}

然后你可以遍历两个字典,比较键并将奇数保存到列表或类似的东西中。你可以通过做这样的事情来做到这一点(如果你有理由相信两个字典都有相同的字母作为键):

mismatched_values = []
for key in dict1:
  if dict1[key] != dict2[key]:
    mismatched_values.append(str(key) + ":" + str(dict1[key]) + "|" + str(key) + ":" + str(dict2[key])

然后可以将mismatched_values参数再次输出到txt文件中

在你的情况下,你需要阅读 python 字典中的所有内容,然后比较它们并在 output.txt 文件中打印输出

with open("a.txt", "r") as first_file:
    with open("b.txt", "r") as second_file:
        first_dict = {}
        second_dict = {}
        for i in first_file.readlines():
            first_dict[i.split(':')[0]] = i.split(':')[1].replace("\n", "").replace(" ", "")
        for i in second_file.readlines():
            second_dict[i.split(':')[0]] = i.split(':')[1].replace("\n", "").replace(" ", "")
with open("report.txt", "w+") as out_file:
    for i in first_dict.keys():
        if first_dict[i] != second_dict[i]:
            out_file.write("{a}:{b}|{a}:{c}\n".format(a=i, b=first_dict[i], c=second_dict[i]))

首先,将文件中的键值对存储在字典中,删除空格和'\n'(剥离方法):

d = dict()
for path in file_paths:
    with open(path, 'r') as f:
      for line in f:
        key, value = line.strip().replace(' ', '').split(':')
        if key in d.keys():
          d[key].append(value)
        else:
          d[key] = [value]

然后,如果相应键的值大于 1,则打印值:

for k,v in d.items():
    if len(set(v)) > 1:
      s = [k + ':' + vv for vv in set(v)]
      s = ' | '.join(s)
      print(s)

读取字典中的两个表,迭代第一个表的键以找到第二个表中存在的具有不同值的键,并在列表理解中同时构建输出:

 with open('table1.txt') as f:
    d1 = dict(line.strip().split(': ') for line in f)
    
with open('table2.txt') as f:
    d2 = dict(line.strip().split(': ') for line in f)
    
different = [f'{key}:{value} | {key}:{d2[key]}' 
                 for key, value in d1.items() 
                 if key in d2 and value!=d2[key]]

out = '\n'.join(different)
print(out)
# b:4 | b:5

对于每个文件,以及它们的每一行,将它们作为条目添加到字典中。最后,比较两个字典的条目,并将不匹配的条目写入文件。

def count_words(file, dict):
    for line in file:
        key_value = line.split(":")
        key = key_value[0]
        dict[key] = key_value[1].strip()


dict1 = {}
dict2 = {}
with open("table1.txt", "r") as file1:
    with open("table2.txt", "r") as file2:
        count_words(file2, dict2)
    count_words(file1, dict1)


with open("output.txt", "w") as f:
    for k in dict1:
        if dict1[k] != dict2[k]:
            f.write("{0}:{1} | {0}:{2}\n".format(k, dict1[k], dict2[k]))