代码之家  ›  专栏  ›  技术社区  ›  oliverbj

Python3-嵌套dict到JSON

  •  0
  • oliverbj  · 技术社区  · 7 年前

    我想把多个 .txt 文件到“类似表”的数据(包括列和行)。每个 .txt文件 文件应视为新列。

    考虑以下内容 .txt文件

    File1.txt

    Hi there
    How are you doing?
    
    What is your name?
    

    File2.txt

    Hi
    Great!
    
    Oliver, what's yours?
    

    我创建了一个简单的方法,它接受file和integer(来自另一个方法的文件号):

    def txtFileToJson(text_file, column):
    
        data = defaultdict(list)
    
        i = int(1)
        with open(text_file) as f:
    
            data[column].append(column)
    
            for line in f:
                i = i + 1
                for line in re.split(r'[\n\r]+', line):
                    data[column] = line
    
        with open("output.txt", 'a+') as f:
            f.write(json.dumps(data))
    

    所以上面的方法将运行两次(每个文件一次,并附加数据)。

    这是 output.txt 运行脚本后的文件:

    {"1": "What is your name?"}{"2": "Oliver, what's yours?"}
    

    如您所见,我只能让它为我的每个文件创建一个新的,然后添加整行。

    [{
       "1": [{
           "1": "Hi there",
           "2": "How are you doing?",
           "3": "\n"
           "4": "What is your name?"
       },
       "2": [{
           "1": "Hi"
           "2": "Great!",
           "3": "\n",
           "4": "Oliver, what's yours?"
       },
    }]
    

    好吧,我玩了一会儿,离得更近了:

    myDict = {str(column): []}
    i = int(1)
    with open(text_file) as f:
        for line in f:
            # data[column].append(column)
            match = re.split(r'[\n\r]+', line)
            if match:
                myDict[str(column)].append({str(i): line})
                i = i + 1
    
    with open(out_file, 'a+') as f:
        f.write(json.dumps(myDict[str(column)]))
    

    下面是输出:

    [{"1": "Hi there\n"}, {"2": "How are you doing?\n"}, {"3": "\n"}, {"4": "What is your name?"}]
    [{"1": "Hi\n"}, {"2": "Great!\n"}, {"3": "\n"}, {"4": "Oliver, what's yours?"}]
    

    但如您所见,现在我有多个JSON根元素。

    解决方案

    多亏了乔尼弗里斯,我做到了:

     data = defaultdict(list)
    
     for path in images.values():
         column = column + 1
    
         data[str(column)] = txtFileToJson(path, column)
    
     saveJsonFile(path, data)
    

    def saveJsonFile(text_file, data):
    
        basename = os.path.splitext(os.path.basename(text_file))
        dir_name = os.path.dirname(text_file) + "/"
        text_file = dir_name + basename[0] + "1.txt"
    
        out_file = dir_name + 'table_data.txt'
    
        with open(out_file, 'a+') as f:
            f.write(json.dumps(data))
    
    0 回复  |  直到 6 年前
        1
  •  1
  •   jonyfries    7 年前

    您正在函数本身内创建一个新字典。所以每次你传入一个文本文件时,它都会创建一个新的字典。

    def txtFileToJson(text_file, column):
        myDict = {str(column): []}
        i = int(1)
        with open(text_file) as f:
            for line in f:
                # data[column].append(column)
                match = re.split(r'[\n\r]+', line)
                if match:
                    myDict[str(column)].append({str(i): line})
                    i = i + 1
    
        with open(out_file, 'a+') as f:
            f.write(json.dumps(myDict[str(column)]))
    
        return myDict
    
    data = defaultdict(list)
    
    data["1"] = txtFileToJson(text_file, column)
    data["2"] = txtFileToJson(other_text_file, other_column)
    
        2
  •  0
  •   igrinis    7 年前
    def read(text_file):
        data, i = {}, 0
        with open(text_file) as f:
            for line in f:
                i = i + 1
                data['row_%d'%i] = line.rstrip('\n')
        return data
    
    res = {}
    for i, fname in enumerate([r'File1.txt', r'File2.txt']):
        res[i] = read(fname)
    with open(out_file, 'w') as f:
        json.dump(res, f)
    
        3
  •  0
  •   Booboo    7 年前

    首先,如果我理解你试图得到一个字典字典的输出,那么让我观察一下,我所理解的你想要的输出似乎是把整个东西都包含在一个列表中,而且,你在字典中有不平衡的开和闭列表方括号,我将忽略这一点,因为我将忽略随附列表。

    #!python3
    
    import json
    import re
    
    def processTxtFile(text_file, n, data):
        d = {}
        with open(text_file) as f:
            i = 0
            for line in f:
                for line in re.split(r'[\n\r]+', line):
                    i = i + 1
                    d[str(i)] = line
        data[str(n)] = d
    
    
    data = dict()
    processTxtFile('File1.txt', 1, data)
    processTxtFile('File2.txt', 2, data)
    with open("output.txt", 'wt') as f:
        f.write(json.dumps(data))
    

    如果你真的需要嵌套在一个列表中,那么你需要替换一个字典

    data[str(n)] = d
    

    data[str(n)] = [d]