【问题标题】:Reading dictionary from file, modifying, then writing to new file. Python从文件中读取字典,修改,然后写入新文件。 Python
【发布时间】:2021-06-16 11:44:18
【问题描述】:

我正在做一项学校作业,要求我:

  1. 将我之前创建的字典作为字符串写入文件。
  2. 然后将该字典再次导入 python 并反转它
  3. 将倒排字典写入新文件。

我遇到了一些问题...

write2file 函数工作正常,并使用字典创建一个文本文件。但是当需要将其拉回并反转数据时,我收到一个类型错误,抱怨字符串索引必须是整数。我迷路了。任何帮助理解将不胜感激。

我是 python 新手。请温柔 :) 提前感谢您帮助我了解我做错了什么。

<pre><code> 

import os

ChessPlayerProfile = {
    "Matt": [("Rating: ", 2200), ("FIDE ID: 0147632DF"), ("Member Status: ", True)],
    "Will": [("Rating: ", 2200), ("FIDE ID: 3650298MK"), ("Member Status: ", False)],
    "Jithu": [("Rating: ", 1900), ("FIDE ID: 5957200LH"), ("Member Status: ", True)],
    "Lisa": [("Rating: ", 2300), ("FIDE ID: 7719328CX"), ("Member Status: ", False)],
    "Nelson": [("Rating: ", 2500), ("FIDE ID: 6499012XX"), ("Member Status: ", True)],
    "Miles": [("Rating: ", 1600), ("FIDE ID: 4392251TJ"), ("Member Status: ", True)],
}


def write2file():
    with open("chessdict.txt", "w") as f:  # Open file using context manager for memory safety
        f.write(str(ChessPlayerProfile))   # dumping dict to file
                                           # (wanted to use pickle but we need strings per instructions)


def Read_Invert_Write():
    with open("chessdict.txt", "r") as f:       # Read File 1
        TempContent = f.read()                  # assign to temp variable
        invert(TempContent)                     # Invert contents of temp variable
        with open("new_dict.txt", "w") as f:    # create File 2
            f.write(str(TempContent))           # and write new dict from variable contents


def invert(d):                             # Previous function for inverting the dict
    inverse = dict()
    for key in d:                          # Iterate through the list that is saved in dict
        val = d[key]
        for item in val:                   # Check if in the inverted dict the key exists
            if item not in inverse:
                inverse[item] = [key]      # If not then create a new list
            else:
                inverse[item].append(key)
    return inverse


def main():
    write2file()
    Read_Invert_Write()
main()

    </pre></code>

输出:


    Traceback (most recent call last):
      File "/home/vigz/PycharmProjects/pythonProject/copytest.py", line 44, in 
        main()
      File "/home/vigz/PycharmProjects/pythonProject/copytest.py", line 43, in main
        Read_Invert_Write()
      File "/home/vigz/PycharmProjects/pythonProject/copytest.py", line 15, in Read_Invert_Write
        invert(TempContent)
      File "/home/vigz/PycharmProjects/pythonProject/copytest.py", line 32, in invert
        val = d[key]
    TypeError: string indices must be integers

【问题讨论】:

    标签: python file dictionary


    【解决方案1】:

    给定一个文件 f 像你一样创建:

    with open("chessdict.txt", "r") as f:
    

    f.read() 的结果是 str,而不是 dict。结果,当你调用invert(f.read())时,这个:

    for d in key:
        val = key[d]
    

    本质上是遍历f.read() 中的字符 并尝试获取f.read()[character](这不是一个有效的操作)。具体来说,如果chessdict.txt的内容是:

    {"foo": "bar"}
    

    invert(f.read())中的迭代:

    inverse = dict()
    for key in d:
    

    执行为:

    inverse = dict()
    for key in '{"foo": "bar"}':  # Returns '{', '"', 'f', ...
    

    如果chessdict.txt包含JSON编码的字符串,你可以试试:

    import json
    
    with open("chessdict.txt", "r") as f:
        invert(json.load(f))
    

    如果f 的内容可以解组为 JSON,则将返回dict。此时,您不妨重写invert,使其遍历键值:

    def invert(d):
        inverse = dict()
        for key, value in d.items():
            for item in val:
                ...
    

    当需要将字典写入到文件时,你应该避免str(your_dictionary):如果你想把它变成一个JSON编码的字符串,你应该写:

    with open(your_output_file, "w+") as f:
        json.dump(your_dict, f).
    

    这将正确地将其编组为 JSON 格式(避免将 {\"foo\": ...} 等转义字符串写入文件时出现问题)。

    【讨论】:

    • 这很有意义。谢谢你。这一切都让我非常头疼。我已经更新了 write2file 和 Read_Invert_Write 函数。现在我只需要弄清楚如何重写反函数才能正常工作,但我看到了我所问的问题。非常感谢。
    • 我在这个程序的另一个领域遇到了困难。发一篇关于它的新帖子会是“好的”堆栈溢出礼仪吗?
    • 是的,如果需要,您应该创建一个新问题,而不是编辑现有问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-25
    • 1970-01-01
    相关资源
    最近更新 更多