Creating Nested List From String Data With Two Delimiters In Python
I am trying to take a text file 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|4~Beryllium~ Be~9.0122~2~2| and turn it into a nested
Solution 1:
You can try this:
s= "1~Hydrogen~H~1.008~1~1|2~Helium~He~4.002~18~1|3~Lithium~Li~6.94~1~2|4~Beryllium~ Be~9.0122~2~2|"final_data = [b for b in [i.split('~') for i in s.split('|')] if b[0]]
Output:
[['1', 'Hydrogen', 'H', '1.008', '1', '1'], ['2', 'Helium', 'He', '4.002', '18', '1'], ['3', 'Lithium', 'Li', '6.94', '1', '2'], ['4', 'Beryllium', ' Be', '9.0122', '2', '2']]
Solution 2:
s = '1~Hydrogen~H~1.008~1~1|2~Helium~He~4.002~18~1|3~Lithium~Li~6.94~1~2|4~Beryllium~ Be~9.0122~2~2|'
[i.split('~') for i in s.split('|') if i]
#Output
[['1', 'Hydrogen', 'H', '1.008', '1', '1'],
['2', 'Helium', 'He', '4.002', '18', '1'],
['3', 'Lithium', 'Li', '6.94', '1', '2'],
['4', 'Beryllium', ' Be', '9.0122', '2', '2']]
Solution 3:
Try this: Supposing variable data is the string:
data = "1~Hydrogen~H~1.008~1~1|2~Helium~He~4.002~18~1|3~Lithium~Li~6.94~1~2|4~Beryllium~ Be~9.0122~2~2|"parsed_data = [x.split('~') for x in data.split('|') if x]
Modified your code to:
classParser:
def__init__(self, path):
self.file = open(path, "r")
self.unparsed_info = self.file.read()
self.parsed_by_element = []
self.parsed_info = []
self.parse_list('|', '~')
defparse_list(self, delimiter1, delimiter2):
for elements in self.unparsed_info.split(delimiter1):
if elements:
self.parsed_by_element.append(elements.split(delimiter2))
print(self.parsed_by_element)
#OR simply
self.parsed_by_element = [elements.split(delimiter2) for elements in self.unparsed_info.split(delimiter1) if elements]
print(self.parsed_by_element)
Solution 4:
You can do this in a much simpler way, also I'm assuming you need int and float conversions? because your desired output looks that way.
def parse(path):
list_of_lists = []
withopen(path) as file_handle:
for line in file_handle:
forstringin line.split("|"):
ifstring:
list_of_lists.append([int(e) if e.isdigit() elsefloat(e) if "." in e elsestr(e) for e instring.rstrip().split("~") if e != " "])
return list_of_lists
my_filepath = "mytxt.txt"
my_list_of_lists = parse(my_filepath)
results:
forsublistinmy_list_of_lists:
print (sublist)
[1, 'Hydrogen', 'H', 1.008, 1, 1][2, 'Helium', 'He', 4.002, 18, 1][3, 'Lithium', 'Li', 6.94, 1, 2][4, 'Beryllium', ' Be', 9.0122, 2, 2]
Post a Comment for "Creating Nested List From String Data With Two Delimiters In Python"