Python - 将文本内容转换为字典值/键容易 [英] Python - converting textfile contents into dictionary values/keys easily
本文介绍了Python - 将文本内容转换为字典值/键容易的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个包含以下内容的文本文件:
Let's say I have a text file with the following:
line = "this is line 1"
line2 = "this is the second line"
line3 = "here is another line"
line4 = "yet another line!"
我想快速将这些转换为字典键/值,以line *为关键,引号中的文本作为值,同时也删除等号。
And I want to quickly convert these into dictionary keys/values with " line* " being the key and the text in quotes as the value while also removing the equals sign.
在Python中最好的方法是什么?
What would be the best way to do this in Python?
推荐答案
f = open(filepath, 'r')
answer = {}
for line in f:
k, v = line.strip().split('=')
answer[k.strip()] = v.strip()
f.close()
希望这有助于
这篇关于Python - 将文本内容转换为字典值/键容易的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文