用户登录
用户注册

分享至

Python - 轻松将文本文件内容转换为字典值/键

  • 作者: 哦合11
  • 来源: 51数据库
  • 2022-12-05

问题描述

假设我有一个包含以下内容的文本文件:

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()

希望对你有帮助

软件
前端设计
程序设计
Java相关