我有一个文本文件,如下所示:
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
我已经设法将所有这些数据以字典的形式显示出来,以键作为植物名称(例如,{key=Monstera Deliciosa,value=rest-of-info-below-in-list}
下面是我的代码附件
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
for plantname, details in list(plants.items()):
print(f"{plantname}'s info is: {details}")
输出为:
Monstera Deliciosa's info is: ['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)'s info is: ['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']
有没有办法用上面提到的For循环以下面的格式显示它
Monstera Deliciosa's info is:
['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)'s info is:
['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']
这意味着我希望使IDE中的文本像文本文件中的文本一样可读。 提前感谢您的慷慨帮助。:)
@jasonharper和@joshmeranda已经回答了这个问题。基本上,此代码将按照您的需要格式化您的文本:
相关问题 更多 >
编程相关推荐