如何使用字符串操作制作一个漂亮的字典?

2024-10-06 12:07:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前有一个函数,可以读取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

Tags: of数据函数字符串文档txt字典line
2条回答
all_data = {}
with open('atm_moon.txt', 'r') as f_in:
    # skip header
    next(f_in)
    for line in f_in:
        # skip empty lines
        if not line.strip():
            continue
        for item in line.split(';'):
            item = item.split('-')
            all_data[item[0].strip()] = item[1].strip()

print(all_data)

印刷品:

{'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'}

嗯,我在这里使用pprint使它以更易于阅读的形式打印词典

请注意,为了隔离由“;”分隔的元素,您还需要在每行内部进行迭代

然后,您可以将每个数据段放入自己的变量中,并使用replace()string方法删除逗号

最后,我们使用float()内置函数来转换数据类型

import pprint

with open('atm_moon.txt') as document:
    document.readline() #skip unwanted information
    elements={} #empty dictionary of the composition of elements

    for line in document:
        if not line.strip():  # skip empty lines
             continue
        for element_info in line.split(';'):
            element_info = element_info.split('-')
            element_name = element_info[0].strip()
            est_composition = float(element_info[1].strip().replace(",", ""))
            elements[element_name] = est_composition

pprint.pprint(elements)

结果:

{'Ammonia': 1000.0,
 'Argon 36': 2000.0,
 'Argon 40': 30000.0,
 'Carbon Dioxide': 1000.0,
 'Helium 4': 40000.0,
 'Hydrogen': 35000.0,
 'Methane': 1000.0,
 'Neon 20': 40000.0,
 'Neon 22': 5000.0}

请注意,这些浮点数将自动显示为一个小数位,但如果需要,您可以使用字符串格式工具在不显示浮点数的情况下向用户显示浮点数

相关问题 更多 >