从Python中的选项卡文件中的特定行逐行读取

时间:2017-08-02 10:59:59

标签: python

我试图从特定行的标签文件中读取,我想逐行处理信息,以便创建包含这些行的列表。我阅读了文档,但我找不到有用的东西。

为了更清楚,我将举一个例子: 鉴于文件:

id对话

  1. 你好,你好吗
  2. 我很好,谢谢你的提问
  3. 我很高兴听到
  4. 我想阅读会话行并创建如下列表:

    list=['Hello,How are you', 'I am fine, thanks for asking', 'I am glad to hear that']
    

1 个答案:

答案 0 :(得分:0)

这是一个oneliner的例子:

import io

file="""id conversation

1 Hello, How are you

2 I am fine, thanks for asking

3 I am glad to hear that"""

[' '.join(row.strip('\n').split(" ")[1:]) for row in io.StringIO(file).readlines() if row.strip('\n')][1:]

打印

['Hello, How are you',
 'I am fine, thanks for asking',
 'I am glad to hear that']
import io

file="""id conversation

1 Hello, How are you

2 I am fine, thanks for asking

3 I am glad to hear that"""

with open("test.txt", "w") as f:
    f.write(file)

with open("test.txt") as f:
    mylist = [' '.join(row.strip('\n').split(" ")[1:]) for row in f.readlines() if row.strip('\n')][1:]

mylist