如何将变量数据读入字典?

2024-10-02 22:25:09 发布

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

我需要将常量的名称及其对应的values.txt文件提取到dictionary。其中key = NameOfConstantsValue=float。你知道吗

file的开头如下所示:

speed of light             299792458.0        m/s
gravitational constant     6.67259e-11        m**3/kg/s**2
Planck constant            6.6260755e-34      J*s
elementary charge          1.60217733e-19     C   

我如何容易地得到常量的name?你知道吗

这是我的尝试:

with open('constants.txt', 'r') as infile:
    file1 = infile.readlines()
    constants = {i.split()[0]: i.split()[1] for i in file1[2:]}

我对split()的理解不对,我需要一点修正!你知道吗


Tags: 文件keytxt名称dictionaryvaluefloatfile1
3条回答

从您的文本文件中,我无法获得要拆分的空格数的正确值。所以下面的代码是为帮助您而设计的。请看一看,它为您工作上述文件。你知道吗

import string
valid_char = string.ascii_letters + ' '
valid_numbers = string.digits + '.'

constants = {}
with open('constants.txt') as file1:
    for line in file1.readlines():
        key = ''
        for index, char in enumerate(line):
            if char in valid_char:
                key += char
            else:
                key = key.strip()
                break
        value = ''

        for char in line[index:]:
            if char in valid_numbers:
                value += char
            else:
                break

        constants[key] = float(value)

print constants

你试过用正则表达式吗? 例如

([a-z]|\s)*

匹配行的第一部分,直到常量的数字开始。你知道吗

Python提供了一个非常好的正则表达式(regex)教程 https://docs.python.org/2/howto/regex.html

你也可以在网上试试你的正则表达式 https://regex101.com/

{' '.join(line.split()[:-2]):' '.join(line.split()[-2:]) for line in lines}

相关问题 更多 >