我需要将常量的名称及其对应的values
从.txt
文件提取到dictionary
。其中key = NameOfConstants
和Value=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()
的理解不对,我需要一点修正!你知道吗
从您的文本文件中,我无法获得要拆分的空格数的正确值。所以下面的代码是为帮助您而设计的。请看一看,它为您工作上述文件。你知道吗
你试过用正则表达式吗? 例如
匹配行的第一部分,直到常量的数字开始。你知道吗
Python提供了一个非常好的正则表达式(regex)教程 https://docs.python.org/2/howto/regex.html
你也可以在网上试试你的正则表达式 https://regex101.com/
相关问题 更多 >
编程相关推荐