python中列表的定界符是什么,在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 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], [4, Beryllium, Be, 9.0122, 2, 2]]

The code I have looks like:

class Parser:

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('|', '~')

def parse_list(self, delimiter1, delimiter2):

for elements in self.unparsed_info.split(delimiter1):

e = elements.strip(delimiter1)

if e != '':

self.parsed_by_element.append(e)

for properties in e.split(delimiter2):

p = properties.strip(delimiter2)

if p != '':

self.parsed_by_element.insert("something that represents location of current element being manipulated", p)

but I can't figure out how to fill in the blank for the insertion on the last line. Does anybody have any suggestions? Or a better way to do this?

解决方案

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 = []

with open(path) as file_handle:

for line in file_handle:

for string in line.split("|"):

if string:

list_of_lists.append([int(e) if e.isdigit() else float(e) if "." in e else str(e) for e in string.rstrip().split("~") if e != " "])

return list_of_lists

my_filepath = "mytxt.txt"

my_list_of_lists = parse(my_filepath)

results:

for sublist in my_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]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值