python - 从文本文件填充字典?
问题描述
所以我有一个看起来像这样的文本文件:
Monstera Deliciosa
2018-11-03 18:21:26
Tropical/sub-Tropical plant
Leathery leaves, mid to dark green
Moist and well-draining soil
Semi-shade/full shade light requirements
Water only when top 2 inches of soil is dry
Intolerant to root rot
Propagate by cuttings in water
Strelitzia Nicolai (White Birds of Paradise)
2018-11-05 10:12:15
Semi-shade, full sun
Dark green leathery leaves
Like lots of water,but soil cannot be water-logged
Like to be root bound in pot
Alocasia Macrorrhizos
2019-01-03 15:29:10
Tropical asia
Moist and well-draining soil
Leaves and stem toxic upon ingestion
Semi-shade, full sun
Like lots of water, less susceptible to root rot
Susceptible to spider mites
我想从此文件中创建一个字典,其中植物的名称作为字典的键,其余信息作为值放入列表中。到目前为止,我已经设法将每种植物及其各自的信息作为列表中的一个项目获取,但我不确定如何将其转换为字典。
with open('myplants.txt', 'r') as f:
contents = f.read()
contents = contents.rstrip().split('\n\n')
contents = [x.replace('\n', ', ') for x in contents]
print(contents)#[0].split(',',0)[0])
预期输出:
plants = {'Monstera Deliciosa':['2018-11-03 18:21:26', 'Tropical/sub-Tropical plant', 'Leathery leaves, mid to dark green', 'Moist and well-draining soil', 'Semi-shade/full shade light requirements', 'Water only when top 2 inches of soil is dry', 'Intolerant to root rot', 'Propagate by cuttings in water'], 'Strelitzia Nicolai (White Birds of Paradise)': ... }
我愿意接受更好的字典应该是什么样子的格式。
解决方案
这是一个可扩展的解决方案,可避免读取内存中的整个文件。
它利用了文本文件可以用作产生每一行的迭代器这一事实
import itertools as it
plants = {}
with open('myplants.txt') as f:
while True:
try:
p = next(f).rstrip()
plants[p] = list(l.rstrip() for l in it.takewhile(lambda line: line != '\n', f))
except StopIteration:
break
print(plants)
生产
{
'Monstera Deliciosa': ['2018-11-03 18:21:26', 'Tropical/sub-Tropical plant', 'Leathery leaves, mid to dark green', 'Moist and well-draining soil', 'Semi-shade/full shade light requirements', 'Water only when top 2 inches of soil is dry', 'Intolerant to root rot', 'Propagate by cuttings in water'],
'Strelitzia Nicolai (White Birds of Paradise)': ['2018-11-05 10:12:15', 'Semi-shade, full sun', 'Dark green leathery leaves', 'Like lots of water,but soil cannot be water-logged', 'Like to be root bound in pot'],
'Alocasia Macrorrhizos': ['2019-01-03 15:29:10', 'Tropical asia', 'Moist and well-draining soil', 'Leaves and stem toxic upon ingestion', 'Semi-shade, full sun', 'Like lots of water, less susceptible to root rot', 'Susceptible to spider mites']
}
推荐阅读
- jenkins - 使用凭证将声纳添加到 Maven Jenkins 作业失败
- excel - 如何标记具有重复名称且条件值小于 20 的项目?
- odoo-12 - 从“Leaves Second Approve”编辑通知内容
- javascript - Wordpress 似乎不接受 css 音乐播放器的 @keyframes
- reactjs - Semantic UI React 下拉菜单未设置值 onChange: React+ Typescript
- jquery - 如何在 Jquery 中根据 td 值对 tr 进行排序
- mysql - 如何使用 Navicat 或 MySQL Workbench 将 MySQL 与 Docker 连接?
- r - R - cowplot:使用 plot_grid 排列 png 图像和 ggplot
- python - 在调用不同文件的函数中,有多少单词以某个字符结尾?
- javascript - 间接点击提交按钮不会设置 $_POST['submit']