【问题标题】:How can I split a text file with # as separator and then split the lines inside the separated part?如何使用 # 作为分隔符拆分文本文件,然后拆分分隔部分内的行?
【发布时间】:2021-04-07 14:18:12
【问题描述】:

我有一个文本文件,其模式类似于

#
a,b
c,d
#
e,f
g,h

我希望打印结果,因为分隔的每个块都是一个元素,块中的每一行都是块一的子元素

[[[a, b], [c, d]], [[e, f], [g, h]]]

这是我的代码,有什么建议可以从这里得到结果吗?谢谢

    ret_list = []

    a = open(file_name,'r')
    content = a.read()
    content = content.split('#')
    for l in content:
        l = l.strip().split('\n')
        for elem in l:
            temp = []
            elem = elem.split(',')
            if '' not in elem:
                temp.append(elem)
            ret_list.append(temp)
    
    a.close() 

我得到的结果

[[], [['a', 'b']], [['c', 'd']], [['e', 'f']], [['g', 'h']]]

【问题讨论】:

  • 这段代码实际做的和你想要做的有什么区别?
  • 好吧,我的想法是先拆分由#分隔的部分,然后拆分这些部分中的行。但是,我正在努力将同一部分中的行返回为一个列表,导致我的代码有两个子列表而不是一个 [[a, b]]、[[c,d]] 中的两个元素而不是 [ [a, b], [c,d] ]

标签: python-3.x list split


【解决方案1】:

您正在为每一行创建temp = [] - 但您想为每个“块”创建它 - 所以您将它移到内部 for 循环之外。 (ret_list.append() 也一样)

content = content.split('#')
for l in content:
    l = l.strip().split('\n')
    temp = []
    for elem in l:
        elem = elem.split(',')
        if '' not in elem:
            temp.append(elem)
    ret_list.append(temp)

这给了你

[[], [['a', 'b'], ['c', 'd']], [['e', 'f'], ['g', 'h']]]

您可以在追加之前添加一个检查 temp 不为空。

if temp:
    ret_list.append(temp)

避免前导空“块”的另一种方法是在拆分前剥离

content.strip('#').split('#')

最后,我会这样写。

ret_list = []

for block in content.strip('#').split('#'):
    lines = block.strip().splitlines()
    lines = [ line.split(',') for line in lines ]
    ret_list.append(lines)

【讨论】:

  • 绝对正确,我刚刚发现 temp = [ ] 在每行循环后都会变回空。不过您的最终建议要好得多,谢谢您的帮助
【解决方案2】:
for l in content:
    l = l.strip().split('\n')
    k=[]
    for elem in l:
        temp=[]
        elem = elem.split(',')
        if '' not in elem:
            temp.append(elem)
            k=k+temp
    if k!=[]:
        ret_list.append (k)
print (ret_list)

我创建了一个新列表 k 来存储一个包含两个块的块,即[['a', 'b'], ['c', 'd']],然后如果 k 列表不为空,则添加到 ret_list

输出

[[['a', 'b'], ['c', 'd']], [['e', 'f'], ['g', 'h']]]

【讨论】:

  • 谢谢你的建议,我刚刚解决了这个问题,它不在 k 上,而是因为临时列表声明应该在第二个循环之外,所以它可以包含两个要添加的元素在结果列表中,然后将自身刷新回 [ ]。不过,感谢您的帮助
猜你喜欢
  • 1970-01-01
  • 2022-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-15
  • 2013-05-30
  • 2014-10-03
  • 2011-09-06
相关资源
最近更新 更多