我目前有一个函数,可以读取txt文档,它可以输出数据并将其放入字典中。但是,我希望字典看起来漂亮,删除每个字符串键中的前导和尾随空格,删除所有逗号并将它们转换为浮点数。例如,我希望霓虹灯看起来像:’NEON 20’: 40000
这是我运行时的打印:
{'Helium': ['4', '-', '40,000', ';', 'Neon', '20', '-', '40,000', ';',
'Hydrogen', '-', '35,000'], 'Argon': ['40', '-', '30,000', ';', 'Neon', '22',
'-', '5,000', ';', 'Argon', '36', '-', '2,000'], 'Methane': ['-', '1000', ';',
'Ammonia', '-', '1000', ';', 'Carbon', 'Dioxide', '-', '1000']}
我的代码如下:
with open('atm_moon.txt') as document:
document.readline() #skip unwanted information
elements={} #empty dictionary of the composition of elements
for line in document:
line = line.split()
if not line: #empty line
continue
elements[line[0]]=line[1:]
print(elements
印刷品:
嗯,我在这里使用
pprint
使它以更易于阅读的形式打印词典请注意,为了隔离由“;”分隔的元素,您还需要在每行内部进行迭代
然后,您可以将每个数据段放入自己的变量中,并使用
replace()
string方法删除逗号最后,我们使用
float()
内置函数来转换数据类型结果:
请注意,这些浮点数将自动显示为一个小数位,但如果需要,您可以使用字符串格式工具在不显示浮点数的情况下向用户显示浮点数
相关问题 更多 >
编程相关推荐