将文本文件中的多行拆分为列表列表

时间:2012-05-23 21:22:05

标签: python

我正在使用文本文件ex:

blahblahblahblahblahblahblah
blahblahblahblahblahblahblah
start
important1a important1b
important2a important2b
end
blahblahblahblahblahblahblah

我想要的是获得像

这样的输出
["'important1a', 'important1b'", "'important2a', 'important2b'"]

每个重要的行被分成单独的元素,但它们在一个列表中按行分组。

我已经接近了这个:

import shlex

useful = []
with open('test.txt', 'r') as myfile:
    for line in myfile:
        if "start" in line:
            break
    for line in myfile:
        if "end" in line:
            break       
        useful.append(line)

data = "".join(useful)

split_data = shlex.split(data)
print split_data

输出:

['important1a', 'important1b', 'important2a', 'important2b']

行之间没有区别。

如何修改此项以区分每一行?谢谢!

3 个答案:

答案 0 :(得分:2)

列出对救援的理解:

[", ".join(map(repr, ln.split())) for ln in open("test.txt")
                                  if "important" in ln]

返回

["'important1a', 'important1b'", "'important2a', 'important2b'"]

答案 1 :(得分:0)

这样的事情怎么样:

useful = []
for line in open('test.txt'):
    parts = line.split()
    if parts[1:]:
        useful.append("'%s'" % "', '".join(parts))

print useful

答案 2 :(得分:0)

您可以使用列表推导。您的代码如下:

useful = []
with open('test.txt', 'r') as myfile:
    for line in myfile:
        if "start" in line:
            break
    for line in myfile:
        line = line.strip()
        if "end" in line:
            break       
        useful.append(line)

print(["'%s'" % ','.join(elem.split(' ')) for elem in useful])