#coding=utf-8
# 请在此处填写代码
#********** Begin **********#
path = 'testdata.txt'
ifile = open(path, 'r')
ifile.readline()
ifile.readline()
global constants
constants = {}
for line in ifile:
alist = list(line.split())
name = ''
for string in alist:
try:
float(string)
value = eval(string)
name.rstrip()
constants[name] = value
break
except:
name = name + string + ' '
print(constants)
ifile.close()
testdata.txt内容
name of constant value dimension
------------------------------------------------------------
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
Avogadro number 6.0221367e23 1/mol
Boltzmann constant 1.380658e-23 J/K
electron mass 9.1093897e-31 kg
proton mass 1.6726231e-27 kg
执行结果
{'speed of light ': 299792458.0, 'gravitational constant ': 6.67259e-11, 'Planck constant ': 6.6260755e-34, 'elementary charge ': 1.60217733e-19, 'Avogadro number ': 6.0221367e+23, 'Boltzmann constant ': 1.380658e-23, 'electron mass ': 9.1093897e-31, 'proton mass ': 1.6726231e-27}
# 这是demo
_dict = {}
with open('test1.txt', 'r', encoding='utf-8') as fb:
rows = fb.readlines()
for row in rows:
tips = row.split('1')
print(tips)
for tip in tips:
_dict[tip] = tip.rstrip()
print(_dict)