从文件中读取字典,修改,然后写入新文件。python
我正在做一项学校作业,要求我:从文件中读取字典,修改,然后写入新文件。python,python,file,dictionary,Python,File,Dictionary,我正在做一项学校作业,要求我: 将我以前创建的字典作为字符串写入文件 然后再次将该字典导入python并将其反转 将倒排字典写入新文件 我有一些问题 write2file函数工作正常,可以使用字典创建文本文件。但是,当要把它拉回来并反转数据时,我得到一个类型错误,抱怨字符串索引必须是整数。我迷路了。如有任何帮助,请谅解 我是python新手。请温柔一点:)提前谢谢你帮我理解我做错了什么 <pre><code> import os ChessPlayerProfile
<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>
导入操作系统
棋手档案={
“马特”:[(“评级:,2200),(“FIDE ID:0147632DF”),(“会员身份:,真实)],
“遗嘱”:[(“评级:,2200),(“FIDE ID:3650298MK”),(“会员身份:,虚假)],
“JITU”:[(“评级:,1900),(“FIDE ID:5957200LH”),(“会员身份:,真实)],
“Lisa”:[(“评级:”,2300),(“FIDE ID:7719328CX”),(“会员身份:”,假)],
“Nelson”:[(“评级:,2500),(“FIDE ID:6499012XX”),(“会员身份:,真实)],
“里程”:[(“评级:,1600),(“国际开发协会ID:4392251TJ”),(“会员身份:,真实)],
}
def write2file():
将open(“chessdict.txt”、“w”)作为f:#使用上下文管理器打开文件以确保内存安全
f、 写入(str(ChessPlayerProfile))#将dict转储到文件
#(想要使用pickle,但我们需要按照说明使用字符串)
def Read_Invert_Write():
以open(“chessdict.txt”、“r”)作为f:#读取文件1
TempContent=f.read()#分配给临时变量
反转(TempContent)#反转temp变量的内容
将open(“new_dict.txt”,“w”)作为f:#创建文件2
f、 写入(str(TempContent))#并从可变内容中写入新的dict
def反转(d):#用于反转dict的上一个函数
逆=dict()
对于输入d:#遍历保存在dict中的列表
val=d[键]
对于val中的项:#检查反转的dict中是否存在键
如果项目不是相反的:
反向[项目]=[关键点]#如果没有,则创建一个新列表
其他:
反向[项]。追加(项)
反向返回
def main():
write2file()
读、反、写()
main()
输出:
with open("chessdict.txt", "r") as f:
回溯(最近一次呼叫最后一次):
文件“/home/vigz/PycharmProjects/pythonProject/copytest.py”,第44行,在
main()
文件“/home/vigz/PycharmProjects/pythonProject/copytest.py”,第43行,在main中
读、反、写()
文件“/home/vigz/PycharmProjects/pythonProject/copytest.py”,第15行,读写颠倒
反转(临时内容)
文件“/home/vigz/PycharmProjects/pythonProject/copytest.py”,第32行,反向
val=d[键]
TypeError:字符串索引必须是整数
给定一个文件f
,如您所创建:
for d in key:
val = key[d]
f.read()
的结果是str
,而不是dict
。因此,当您调用invert(f.read())
时:
{"foo": "bar"}
基本上是在f.read()
中的字符上进行迭代,并尝试获取f.read()[character]
(这不是有效的操作)。具体地说,如果chessdict.txt的内容是:
inverse = dict()
for key in d:
invert(f.read())
中的迭代:
其执行方式如下:
import json
with open("chessdict.txt", "r") as f:
invert(json.load(f))
如果chessdict.txt
包含JSON编码的字符串,您可以尝试:
def invert(d):
inverse = dict()
for key, value in d.items():
for item in val:
...
如果f
的内容可以解组为JSON,则返回dict
。此时,您不妨重写invert
,使其在键和值上迭代:
当需要将字典写入文件时,应避免使用str(您的字典):如果要将其转换为JSON编码的字符串,应编写:
这将正确地将其打包成JSON格式(避免将转义字符串(如
{\'foo\':…}
写入文件)的问题)。这很有意义。非常感谢。这一切对我来说都是非常伤脑筋的。我已经更新了write2文件和Read_Invert_Write函数。现在我只需要弄清楚如何重写反函数来正确工作,但我看到了我所问的问题。非常感谢。我在这个项目的另一个领域遇到了困难。写一篇关于这个问题的新帖子“可以”吗?是的,如果需要,你应该创建一个新的问题,而不是编辑现有的问题。
import json
with open("chessdict.txt", "r") as f:
invert(json.load(f))
def invert(d):
inverse = dict()
for key, value in d.items():
for item in val:
...
with open(your_output_file, "w+") as f:
json.dump(your_dict, f).