I have a text file as a database for properties of periodic elements using ~ as a delimiter to separate properties and | to separate different elements which looks like this:
1~Hydrogen~H~1.008~1~1|2~Helium~He~4.002~18~1|3~Lithium~Li~6.94~1~2|
and so on... I am trying to parse the whole thing into a list that looks like this:
["1~Hydrogen~H~1.008~1~1", "2~Helium~He~4.002~18~1", "3~Lithium~Li~6.94~1~2"]
This is the code have, and I am intentionally making it a class:
class Parser:
def __init__(self, path):
self.file = open(path, "r")
self.unparsed_info = self.file.read()
self.element_list = ['']
def parse_file(self, delimiter):
for elements in self.unparsed_info.split(delimiter):
self.element_list.insert(eval(elements.strip(delimiter)))
def print_unparsed(self):
print(self.unparsed_info)
def print_parsed(self):
print(self.element_list)
def close_file(self):
self.file.close()
Element_properties = Parser("element_properties.txt")
Element_properties.parse_file('|')
Element_properties.print_parsed()
Element_properties.close_file()
But as many of you can probably tell, this prints the entire text file into every element of the list. How can I change the parse_file function so that it only puts one segment into each element of the element_list?
eval?