将文本文件转换成字典 [英] Convert a text file into a dictionary
本文介绍了将文本文件转换成字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个这种格式的文本文件:
I have a text file in this format:
key:object,
key2:object2,
key3:object3
如何通过以下步骤将其转换成Python字典?
How can I convert this into a dictionary in Python for the following process?
- 打开
- 检查字符串
s
=词典中的任何键 - 如果是,则字符串
s
=链接到上述键的对象. - 否则,什么也没发生
- 文件关闭.
- Open it
- Check if string
s
= any key in the dictionary - If it is, then string
s
= the object linked to the aforementioned key. - If not, nothing happens
- File closes.
我尝试了以下代码以逗号分隔,但输出不正确.它使文本文件中的键和对象的组合成为单个键和单个对象,从而有效地复制了它:
I've tried the following code for dividing them with commas, but the output was incorrect. It made the combination of key and object in the text file into a single key and single object, effectively duplicating it:
代码:
file = open("foo.txt","r")
dict = {}
for line in file:
x = line.split(",")
a = x[0]
b = x[0]
dict[a] = b
错误的输出:
key:object, key:object
key2:object2, key2:object2
key3:object3, key3:object3
谢谢
推荐答案
m={}
for line in file:
x = line.replace(",","") # remove comma if present
y=x.split(':') #split key and value
m[y[0]] = y[1]
这篇关于将文本文件转换成字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文