How to read variating data into dictionary?
How to read variating data into dictionary?
I need to extract the name of the constants and their corresponding values
from a .txt file
into a dictionary
. Where key = NameOfConstants
and Value=float
.
The start of the file
looks like this:
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
How do I get the name
of the constants easy?
This is my attempt:
with open('constants.txt', 'r') as infile: file1 = infile.readlines() constants = {i.split()[0]: i.split()[1] for i in file1[2:]}
I'm not getting it right with the split()
, and I need a little correction!
Answer by Joern Boegeholz for How to read variating data into dictionary?
Have You tried using regular expressions? for example
([a-z]|\s)*
matches the first part of a line until the digits of the constants begin.
Python provides a very good tutorial on regular expressions (regex) https://docs.python.org/2/howto/regex.html
You can try out your regex online as well https://regex101.com/
Answer by Juraj Bezruka for How to read variating data into dictionary?
{' '.join(line.split()[:-2]):' '.join(line.split()[-2:]) for line in lines}
Answer by SIslam for How to read variating data into dictionary?
What about 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:]))
Or use oneliner to make dictionary-
{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() ]}
Output-
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'}
Answer by AnkurJatt for How to read variating data into dictionary?
From your text file I'm unable to get the correct value of no of spaces to split. So below code is designed to help you. Please have a look, it worked for you above stated file.
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
Answer by Thomas for How to read variating data into dictionary?
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:]}
Since there were two lines above not needed.
Answer by Ytsen de Boer for How to read variating data into dictionary?
This would best be solved using a regexp.
Focussing on your question (how to get the names) and your desires (have something shorter):
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
Fatal error: Call to a member function getElementsByTagName() on a non-object in D:\XAMPP INSTALLASTION\xampp\htdocs\endunpratama9i\www-stackoverflow-info-proses.php on line 72
0 comments:
Post a Comment