簡體   English   中英

如何使用 Python 從給定的文本文件將表添加到字典?

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

假設我們有兩個文本文件,每個文件都包含一個表格,例如:

表1.txt

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

表2.txt

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

我想將這些表添加到 Python 字典中,然后比較條目,以便將不匹配的結果轉儲到 output 文件中。 在上面的例子中

output.txt

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

我會這樣做:

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)

首先,將文件中的鍵值對存儲在字典中,刪除空格和 '\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)

讀取字典中的兩個表,迭代第一個表的鍵以查找第二個表中存在的具有不同值的鍵,並在列表理解中同時構建 output:

 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

我可能會將每個文件讀入他們自己的字典。 所以閱讀文件,將字母指定為鍵,將數字指定為值,這意味着你會得到兩個這樣的字典:

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參數output到一個txt文件。

在您的情況下,您需要閱讀 python 字典中的所有內容,然后比較它們並在 output.txt 文件中打印 output

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM