2016-01-18 31 views
1

我需要從.txt file中提取常量的名稱及其相應的valuesdictionary。其中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()得到它,我需要一點點的修正!

+0

是你的「constantts」與製表符分隔?如果是,stdlib的'csv'模塊就是你的朋友。 –

+0

不,他們是經常性的空間。 – Thomas

+0

uhu,這很糟糕......這應該是最終用戶可編輯的配置文件嗎? –

回答

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

您是否嘗試過使用正則表達式? 例如

([a-z]|\s)* 

一個線的第一部分相匹配,直到常量的數字開始。

Python的正則表達式提供了一個很好的教程(正則表達式) https://docs.python.org/2/howto/regex.html

你可以嘗試一下你的正則表達式在線以及 https://regex101.com/

0

什麼re.split -

import re 
lines = open(r"C:\txt.txt",'r').readlines() 
for line in lines: 
    data = re.split(r'\s{3,}',line) 
    print "{0} : {1}".format(data[0],''.join(data[1:])) 

或使用字首製作字典 -

{k:v.strip() for k,v in [(re.split(r'\s{3,}',line)[0],''.join(re.split(r'\s{3,}',line)[1:])) for line in open(r"C:\txt.txt",'r').readlines() ]} 

輸出 -

gravitational constant : 6.67259e-11m**3/kg/s**2 

Planck constant : 6.6260755e-34J*s 

elementary charge : 1.60217733e-19C 

Dictionary-

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

從你的文本文件,我無法得到的無空格的正確值分割。所以下面的代碼旨在幫助你。請看一下,它在上述文件中爲你工作。

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 
+0

這是相當不錯的,它的工作文件即時提取,但我希望有更短的東西:) :) – Thomas

+0

嗯是的,它是一個很長的路要走:P只有當我們知道什麼是分裂常數的正確值時,我們才能輕易地縮短它的長度。例如,如果它的'tab','\ t'比你的代碼可以正常工作,並且在最後一行中有一點點替換,像這樣... constants = {i.split('\ t')[0]:i.split '\ t')[1] for file1 [2:]} – AnkurJat

+0

@Thomas請在我上面的評論中回答這個問題。如果你的文件是一個製表符分隔值,那麼你__dont__需要任​​何手寫解析代碼... –

0
with open('constants.txt', 'r') as infile: 
    lines = infile.readlines() 
    constants = {' '.join(line.split()[:-2]):float(' '.join(line.split()[-2:-1])) for line in lines[2:]} 

由於有兩行以上沒有必要的。

0

這將最好使用正則表達式來解決。

集中於你的問題(如何獲得的名稱)和你的願望(有一些短):

import re 

# Regular expression fetches all characters 
# until the first occurence of a number 
REGEXP = re.compile('^([a-zA-Z\s]+)\d.*$') 

with open('tst.txt', 'r') as f: 

    for line in f: 

     match = REGEXP.match(line) 

     if match: 

      # On a match the part between parentheses 
      # are copied to the first group 
      name = match.group(1).strip() 

     else: 

      # Raise something, or change regexp :) 
      pass