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

发布于 2024-11-05 17:28:36 字数 256 浏览 0 评论 0原文

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

line = "this is line 1"
line2 = "this is the second line"
line3 = "here is another line"
line4 = "yet another line!"

我想将它们快速转换为字典键/值,其中“ line* ”为键,引号中的文本为值,同时删除等号。

在 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!"

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.

What would be the best way to do this in Python?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

奢华的一滴泪 2024-11-12 17:28:36
f = open(filepath, 'r')
answer = {}
for line in f:
    k, v = line.strip().split('=')
    answer[k.strip()] = v.strip()

f.close()

希望这有帮助

f = open(filepath, 'r')
answer = {}
for line in f:
    k, v = line.strip().split('=')
    answer[k.strip()] = v.strip()

f.close()

Hope this helps

嘿看小鸭子会跑 2024-11-12 17:28:36

一行:

d = dict((line.strip().split(' = ') for line in file(filename)))

In one line:

d = dict((line.strip().split(' = ') for line in file(filename)))
关于从前 2024-11-12 17:28:36

InspectorG4dget 的 urlopen 版本的答案可能如下所示:

from urllib.request import urlopen
url = 'https://raw.githubusercontent.com/sedeh/github.io/master/resources/states.txt'
response = urlopen(url)
lines = response.readlines()
state_names_dict = {}
for line in lines:
    state_code, state_name = line.decode().split(":")
    state_names_dict[state_code.strip()] = state_name.strip()

Here's what the urlopen version of inspectorG4dget's answer might look like:

from urllib.request import urlopen
url = 'https://raw.githubusercontent.com/sedeh/github.io/master/resources/states.txt'
response = urlopen(url)
lines = response.readlines()
state_names_dict = {}
for line in lines:
    state_code, state_name = line.decode().split(":")
    state_names_dict[state_code.strip()] = state_name.strip()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文