我正在加载一个包含单词和定义的文件,每一行都用冒号分隔。这是一个样本。
Dissaray:A state of confusion and disorderliness
Staid:Steady and serious
Contemptible:Unworthy, wretched, mean
Intertwine:To connect or associate two things
Unwarranted:Not based on truth or valid circumstances
Punctuate:To specifically point out
Validate:To state the soundness or truth of something
Conducive:To contribute in a useful way我试图用以下代码读取该文件:
print("Currently loading file for your level")
dictionary = {}
with open("level"+str(level)+".txt","r+") as f:
for line in f:
print line
line.split(":")
dictionary[line[0]] = line[1]
print("Dictionary file has been loaded")
print(dictionary)这些行打印正确,但是当我打印dictionary数组时,我会得到以下内容。{'A': 'p', 'C': 'o', 'B': 'e', 'E': 'm', 'D': 'e', 'G': 'r', 'F': 'i', 'I': 'r', 'H': 'i', 'J': 'o', 'M': 'i', 'L': 'u', 'O': 'p', 'N': 'o', 'P': 'a', 'S': 'u', 'R': 'e', 'U': 'n', 'T': 'r', 'W': 'a', 'V': 'e', 'Z': 'e'}
我不知道这里发生了什么,有人能帮忙吗?
发布于 2017-09-01 11:55:40
str.split不工作在适当的地方。您需要将它分配给line,否则,您将索引原始行:
for line in f:
line = line.split(":")
dictionary[line[0]] = line[1]更重要的是,您也可以简单地这样做:
dictionary = dict(line.split(':') for line in f)从生成器表达式构建字典。
发布于 2017-09-01 11:56:15
问题是.split()返回它的值,而不是修改它的参数。实际上,它必须这样做,因为字符串在Python中是不可变的。所以你只需要改变:
line.split(":")
dictionary[line[0]] = line[1]至
line_parts = line.split(":")
dictionary[line_parts[0]] = line_parts[1]https://stackoverflow.com/questions/45999744
复制相似问题