从文件中读取字典,修改,然后写入新文件。python

2024-06-07 16:22:31 发布

您现在位置:Python中文网/ 问答频道 /正文

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

  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


Tags: keyinidtrueread字典defstatus
1条回答
网友
1楼 · 发布于 2024-06-07 16:22:31

给定一个文件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\": ...})写入文件时出现问题)

相关问题 更多 >

    热门问题