2016-03-05 90 views
-2
N-Heptane 100.20 
Hexane 86.17 
Hydrochloric Acid 36.47 
Hydrogen, H2 2.016 
Hydrogen Chloride 36.461 
Hydrogen Sulfide 34.076 
Hydroxyl, OH 17.01 
Krypton 83.80 
Methane, CH4 16.044 
Methyl Alcohol 32.04 
Methyl Butane 72.15 
Methyl Chloride 50.488 
Natural Gas 19.00 
Neon, Ne 20.179 
Nitric Oxide, NO 30.006 
Nitrogen, N2 28.0134 
Nitrous Oxide, NO2 44.012 
N-Octane 114.22 
Oxygen, O2 31.9988 
Ozone 47.998 
N-Pentane 72.15 
Iso-Pentane 72.15 
Propane, C3H8 44.097 
Propylene 42.08 

這樣的文本內容,我想劈分子式字符串和分子量如何在python中像這樣分割文本文件?

{"Hydrogen, H2":2.016, "Hydrogen Chloride":36.461, etc........} 

回答

2

只需遍歷每一行和使用rsplit檢索最後白 - 空格分隔值作爲字典值。其餘的線路作爲關鍵。

d = {} 
with open(filename) as f: 
    for line in f: 
     key, value = line.rsplit(None, 1) 
     d[key] = float(value) 
+1

你的「簡潔形式」略有不同:它創建'{str:str}',而不是'{str:float}'。 – GingerPlusPlus

+0

thx很多爲你的答案 –

+2

或''di = {k:float(v)for k,v in(line.rsplit(None,1)for line in line)}' – dawg