【问题标题】:How to add a table to dictionary from a given text file using Python?如何使用 Python 将给定文本文件中的表添加到字典中?
【发布时间】:2020-12-10 12:25:47
【问题描述】:

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

table1.txt

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

table2.txt

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

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

输出.txt

b:4 | b:5

感谢您的投入!

【问题讨论】:

    标签: python python-3.x python-2.7


    【解决方案1】:

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

    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]))
    

    【讨论】:

      【解决方案2】:

      首先,将文件中的键值对存储在字典中,删除空格和 '\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)
      

      【讨论】:

        【解决方案3】:

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

         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
        

        【讨论】:

          【解决方案4】:

          我会这样做:

          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)
          

          【讨论】:

          • 我明白了。谢谢。但是,您的代码会转储此输出:a: 1 b | a: 1 b
          • @sam 我已经进行了适当的编辑。很高兴我能帮上忙。
          【解决方案5】:

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

          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文件。

          【讨论】:

          • 您使用的第一个数据结构是dictionary,而不是数组。
          【解决方案6】:

          在您的情况下,您需要阅读 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]))
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2015-03-21
            • 2016-08-13
            • 2018-05-31
            • 1970-01-01
            • 2019-11-25
            • 1970-01-01
            • 2019-05-01
            相关资源
            最近更新 更多