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

Python 将文本文件中的多行拆分为列表列表,python,Python,我正在使用文本文件,例如: blahblahblahblahblahblahblah blahblahblahblahblahblahblah start important1a important1b important2a important2b end blahblahblahblahblahblahblah 我想要的是得到如下输出 ["'important1a', 'important1b'", "'important2a', 'important2b'"] 其中,每一重要行都被拆分

我正在使用文本文件,例如:

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']
线条之间没有区别


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

列出对救援的理解:

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

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

像这样的怎么样:

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

print useful

您可以使用列表理解。您的代码如下所示:

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])

谢谢这似乎可以识别这两行,但我不确定如何用引号区分每一行。@BradConyers:我不确定这是故意的还是意外的,我将修改代码来做到这一点:)@BradConyers:不过看看代码。。。我认为这个想法是错误的。你能告诉我你的目标是什么吗?生成此输出对我来说似乎是个坏主意:)谢谢更新!目标是只有一个变量可以与此结果进行比较。例如x=[“'1a','1b','2a','2b'”]和y=[“'1d','1b','2a','2c'”,如果我比较这两个,那么测试就会失败。这是我的最终目标。我希望这有帮助。@BradConyers:你说得对,我颠倒了引语,它现在起作用了:)你能详细说明一下吗,我不知道“…”代表什么。谢谢@BradConyers:
是交互式Python解释器的继续提示符。你不是自己写的。明白了,所以当我把它实现到我的实际文本文件中时,我得到了很多“a”,其中a在文本文件中已经有引号了。这可能是什么原因造成的?另外,如果有目录路径,它会在目录C:\\\\something中的每个级别之间添加3个额外的反斜杠。